-1

I'm trying to retrieve data from an api using curl with this code:

$xml_data = '<name>foobar%</name>';

$URL = "http://www.example.com/api/foobar.xml";

$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
$output = curl_exec($ch);
curl_close($ch);

When I execute this php script, all works well and the correct xml data is returned in my browser. My question is, how can I parse this data?

(If you recommend I do the whole thing using a different method as curl, feel free to tell me)

Shadow Wizard Says No More War
  • 64,101
  • 26
  • 136
  • 201
Tomi Seus
  • 1,141
  • 2
  • 13
  • 27

3 Answers3

1

You can use following kind of code.

$xml = simplexml_load_string($output);

And if you need to go through it's node you can simply go through those as given in below example.

Ex:

$imageFileName = $xml->Cover->Filename;

If you need you can use xpath as well. Ex:

$nodes = $xml->xpath(sprintf('/lfm/images/image/sizes/size[@name="%s"]', 'extralarge'));

Good luck!

Prasad.

Prasad Rajapaksha
  • 5,926
  • 10
  • 35
  • 51
0

You could use simplexml to parse it

Sudhir Bastakoti
  • 97,363
  • 15
  • 155
  • 158
  • I tried it with simplexml but it won't work. $output seems to be a boolean (tested it with gettype). what shall I do? – Tomi Seus Dec 27 '11 at 10:38
0

Check the PHP docs for curl_exec function - note that the return value will be true/false unless CURLOPT_RETURNTRANSFER is enabled, in which case it will be the results of the call.

Here's an updated example that would return the data in $output, and get the transfer details via curl_getinfo():

$xml_data = 'foobar%';

$URL = "http://www.example.com/api/foobar.xml";

$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

print_r($info);
print_r($output);
BrianC
  • 10,383
  • 2
  • 28
  • 49