Question

I am getting a xml response from doing:

$foo = $client->__doRequest (parameters here)

when I echo out $foo I get the xml exactly as I'm told I should. The problem is now I want to extract some values from the xml. Now the easiest way I can see to do that is to convert it to a php array and then is super simple to get value and do lots of lovely stuff with but I seem to be having trouble doing this. Have seen a lot of examples using simple_load_xml but all I get is 'Notice: Array to string conversion in'. When I var_dump '$foo' I get 'string 'xml' '.

What am I doing wrong?

Was it helpful?

Solution

As suggested by @CD001 I persevered with DOMDocument and figured it out in the end with the following code:

$dom = new DOMDocument;
$dom->loadXML($xml);
$things = $dom->getElementsByTagName('chocolate');

/** I only had a single result so had to do it this way rather then a loop**/

if($things->length > 0) {
  $node = $things->item(0);
  $chocolate = $node->nodeValue;
} 
else {
  // empty result set
}
echo $chocolate;

bah! JSON is so much nicer...

OTHER TIPS

Use Xpath:

$dom = new DOMDocument;
$dom->loadXML($xml);
$xpath = new DOMXpath($dom);

// get content of the first chocolate element node as a string
$chocolate = $xpath->evaluate('string(//chocolate)');

echo $chocolate;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top