Reputation: 9282
I'm receiving through cUrl an XML generated with PHP with this code:
$c = curl_init("http://www.domain.com/script.php");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$xmlstr = curl_exec($c);
If I echo the $xmlstr variable it shows the following:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<XGetPasoParadaREGResponse xmlns="http://tempuri.org/">
<XGetPasoParadaREGResult>
<PasoParada><cabecera>false</cabecera>
<e1>
<minutos>1</minutos>
<metros>272</metros>
<tipo>NORMAL</tipo>
</e1>
<e2>
<minutos>7</minutos>
<metros>1504</metros>
<tipo>NORMAL</tipo>
</e2><linea>28
</linea>
<parada>376</parada>
<ruta>PARQUE ALCOSA</ruta>
</PasoParada>
</XGetPasoParadaREGResult><status>1</status></XGetPasoParadaREGResponse>
</soap:Body>
</soap:Envelope>
Which is correct and the same generated at the script. However, if I try to do the following
$xml = simplexml_load_string($xmlstr);
if (!is_object($xml))
throw new Exception('Reading XML error',1001);
echo $xml->e1->minutos;
Doesn't show anything and print_r the object prints an empty object. What could be wrong?
Upvotes: 1
Views: 2449
Reputation: 51950
You have two main problems, firstly you aren't taking into account any namespaces (e.g. soap
) and secondly you aren't traversing the XML hierarchy to get at the desired element.
The "simple" way would be:
$minutos = (int) $xml
->children('soap', TRUE) // <soap:*>
->Body // <soap:Body>
->children('') // <*> (default/no namespace prefix)
->XGetPasoParadaREGResponse // <XGetPasoParadaREGResponse>
->XGetPasoParadaREGResult // <XGetPasoParadaREGResult>
->PasoParada // <PasoParada>
->e1 // <e1>
->minutos; // <minutos> yay!
You could also make an XPath query for the value:
// Our target node belongs in this namespace
$xml->registerXPathNamespace('n', 'http://tempuri.org/');
// Fetch <minutos> elements children to <e1>
$nodes = $xml->xpath('//n:e1/n:minutos');
// $nodes will always be an array, get the first item
$minutos = (int) $nodes[0];
For what it is worth, the PHP Manual contains basic usage examples covering how to traverse the XML structure and the specific pages for children()
and registerXPathNamespace()
show you how to work with namespaced elements with examples.
Finally, as you have seen, the output from print_r()
/var_dump()
with SimpleXML is not always very helpful at all! The best way to see what you've got is to echo saveXML()
which will display the XML for a given element.
Upvotes: 6
Reputation: 4260
Try the children method:
foreach ($xml->children("soap", true) as $k => $v) {
echo $k . ":\n";
var_dump($v);
}
Upvotes: 1