Reputation: 329
I am trying to parse XML from a web service result but I am failing. The result seems to be valid as I print it and it displays all data I need.
print_r($result);
Gives me:
<?xml version="1.0" encoding="utf-8"?><retorno> <versao>1.00</versao> <versaodados>1.00</versaodados> <codigoconvenio>S2111601391F5530F0250A</codigoconvenio> <codigoretorno>0</codigoretorno> <mensagens> <mensagem>Sucesso</mensagem> </mensagens> <dados> <dado><identificadorfatura>1000219113262</identificadorfatura><mesanoreferencia>ABR/2015</mesanoreferencia><datavencimento>2015-06-07</datavencimento><valorfatura>239.72</valorfatura></dado> </dados></retorno>
Now, I need to get the "codigoretorno" tag contents and I am trying this considering that "retorno" would be the root tag:
$xml = simplexml_load_string($result);
if ($xml === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
} else {
echo 'Codigo Convenio: ';
echo $xml->codigoconvenio;
}
Gives me no errors and just prints "Codigo Convenio: " with nothing following. When I try:
print_r($xml);
I get:
SimpleXMLElement Object ( )
And also:
var_dump($xml);
The output is:
object(SimpleXMLElement)#5 (0) { }
Any suggestions would be welcome!
Upvotes: 1
Views: 851
Reputation: 198117
The PHP code you have actually is not lying to you and does what you've been written down. Probably it's useful to you to comment on some details:
$xml = simplexml_load_string($result);
if ($xml === false) {
...
As you've observed, the false
case is not triggered, so loading the XML was successful.
Then you report on the empty looking print_r SimpleXMLElement output. Now this is a bit unfair. You might have learned from observation that print_r
and var_dump
can be useful in developing and debugging your code. This is especially not true in case of SimpleXMLElement
. In general this is not true, because a step-debugger with breakpoints is far superior than placing var_dump
or print_r
here and there temporarily in your code.
Anyway, for SimpleXMLElement it's specifically not useful. Compare the XML file you oben with a little database. When you create a PDO object to interact with the database for example and you use print_r
or var_dump
on it, would you expect to see the whole content of the database? I bet you won't. This is similar with simplexml. Using print_r
won't show you the XML. It sometimes does show something that resembles the XML structure but only the elements under certain rules which can be pretty specific. By the way, this has always been a point of much befuddlement, a classic in this Q&A is:
Instead, take a look on the XML itself and then query the data you're looking for. As you did. It even does work: https://eval.in/392059.
Upvotes: 1