Posted By

focal55 on 11/06/11


Tagged

curl xml


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

dvertigo


PHP - cURL receives xml


 / Published in: PHP
 

  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. libxml_use_internal_errors(true);
  32. //parse the xml response string
  33. $xmldata = simplexml_load_string($xmlResponse);
  34. //store the original xml in an array
  35. $xml = explode("\n", $xmlResponse);
  36. //if simplexml_load_string() fails, it returns false.
  37. //if it returns false, collect the errors and print them to the screen
  38. if (!$doc) {
  39. $errors = libxml_get_errors();
  40. foreach ($errors as $error) {
  41. echo display_xml_error($error, $xml);
  42. }
  43. libxml_clear_errors();
  44. }else{
  45. //Successfull parsed the xml string
  46. print_r($doc);
  47. }
  48. }else{
  49. //There was a problem with cURL executing. Do you have cURL on this server?
  50. echo "cURL was not able to execute";
  51. //close connection
  52. curl_close($ch);
  53. }
  54.  
  55. //Helper Function For Displaying the Errors
  56. function display_xml_error($error, $xml){
  57. $return = $xml[$error->line - 1] . "\n";
  58. $return .= str_repeat('-', $error->column) . "^\n";
  59. switch ($error->level) {
  60. case LIBXML_ERR_WARNING:
  61. $return .= "Warning $error->code: ";
  62. break;
  63.  
  64. case LIBXML_ERR_ERROR:
  65. $return .= "Error $error->code: ";
  66. break;
  67.  
  68. case LIBXML_ERR_FATAL:
  69. $return .= "Fatal Error $error->code: ";
  70. break;
  71. }
  72. $return .= trim($error->message) .
  73. "\n Line: $error->line" .
  74. "\n Column: $error->column";
  75. if ($error->file) {
  76. $return .= "\n File: $error->file";
  77. }
  78. return "$return\n\n--------------------------------------------\n\n";
  79. }
  80. ?>

Report this snippet  

You need to login to post a comment.