PHP-cURL接收xml

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP-cURL接收xml相关的知识,希望对你有一定的参考价值。

  1. <?php
  2.  
  3. /******************************************
  4.  * POST TO REMOTE SCRIPT
  5.  ******************************************/
  6.  
  7. //fake data to send via cURL
  8. $post = 'var1=hello&var2=world';
  9. //replace with your post destination url
  10. $url = "http://example.com/script.php";
  11. //start cURL
  12. $ch = curl_init();
  13. //define curl: set where the post is going
  14. curl_setopt($ch, CURLOPT_URL, $url);
  15. //define curl: set that you want the response
  16. //to be store in a variable and not display on screen
  17. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  18. //define curl: set what you are sending
  19. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  20.  
  21. //If the post was not successful curl_exec will return false.
  22. //If successful store response in variable
  23. if ($xmlResponse = curl_exec($ch)) {
  24. //close the connection
  25. curl_close($ch);
  26.  
  27. //Trim the response from excess white space
  28. //NOTE:It may be necessary to do further sanitizing of the string
  29. $xmlResponse = trim($xmlResponse);
  30. //enable error reporting
  31. //parse the xml response string
  32. $xmldata = simplexml_load_string($xmlResponse);
  33. //store the original xml in an array
  34. $xml = explode(" ", $xmlResponse);
  35. //if simplexml_load_string() fails, it returns false.
  36. //if it returns false, collect the errors and print them to the screen
  37. if (!$doc) {
  38. $errors = libxml_get_errors();
  39. foreach ($errors as $error) {
  40. echo display_xml_error($error, $xml);
  41. }
  42. }else{
  43. //Successfull parsed the xml string
  44. print_r($doc);
  45. }
  46. }else{
  47. //There was a problem with cURL executing. Do you have cURL on this server?
  48. echo "cURL was not able to execute";
  49. //close connection
  50. curl_close($ch);
  51. }
  52.  
  53. //Helper Function For Displaying the Errors
  54. function display_xml_error($error, $xml){
  55. $return = $xml[$error->line - 1] . " ";
  56. $return .= str_repeat('-', $error->column) . "^ ";
  57. switch ($error->level) {
  58. case LIBXML_ERR_WARNING:
  59. $return .= "Warning $error->code: ";
  60. break;
  61.  
  62. case LIBXML_ERR_ERROR:
  63. $return .= "Error $error->code: ";
  64. break;
  65.  
  66. case LIBXML_ERR_FATAL:
  67. $return .= "Fatal Error $error->code: ";
  68. break;
  69. }
  70. $return .= trim($error->message) .
  71. " Line: $error->line" .
  72. " Column: $error->column";
  73. if ($error->file) {
  74. $return .= " File: $error->file";
  75. }
  76. return "$return -------------------------------------------- ";
  77. }
  78. ?>

以上是关于PHP-cURL接收xml的主要内容,如果未能解决你的问题,请参考以下文章

asmack - 接收自定义 XML 消息

asmack - 接收自定义 XML 消息 ||

WCF 从 XML 接收空模型

http接收xml数据用java怎么实现呀?

(spark-xml) 使用 from_xml 函数解析 xml 列时仅接收 null

H. Ajax对XML信息的接收与处理