GluePear
GluePear

Reputation: 7715

XML error when posting with cURL

I'm posting some XML from one page to another on the same site, using cURL:

I generate the XML from an array (this bit works fine):

$xml = new SimpleXMLElement('<test/>');
array_walk_recursive($arr, array ($xml, 'addChild'));
$xmlxml = $xml->asXML()

Then use cURL to post to another page:

$url = "http://www.test.com/feedtest.php";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlxml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

This produces the error:

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "<?xml version="1.0"?> <test> [....]" in "xxxxx/feedtest.php on line 16"

What am I doing wrong?

I should add this is what's happening on the other page:

if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){ 
    $postFile = file_get_contents('php://input'); 
}
$xml = simplexml_load_file($postFile);

This last line is the line triggering the error.

Upvotes: 1

Views: 671

Answers (1)

hakre
hakre

Reputation: 197766

It's a pretty trivial error, easy to miss:

$postFile = file_get_contents('php://input'); 
            ^^^^^^^^^^^^^^^^^

This puts the XML string into $postFile already. But then you use it as filename:

$xml = simplexml_load_file($postFile);
                      ^^^^

Instead, you can just load it this way:

$postFile = 'php://input';

That is a perfect valid filename. So the code later on should work:

$xml = simplexml_load_file($postFile);

Alternatively you can load strings:

$postFile = file_get_contents('php://input'); 
...
$xml = simplexml_load_string($postFile);

Upvotes: 1

Related Questions