PHP - cURL receives xml


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  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("\n", $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] . "\n";
  56. $return .= str_repeat('-', $error->column) . "^\n";
  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. "\n Line: $error->line" .
  72. "\n Column: $error->column";
  73. if ($error->file) {
  74. $return .= "\n File: $error->file";
  75. }
  76. return "$return\n\n--------------------------------------------\n\n";
  77. }
  78. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.