This is the code i’m using to parse a remote XML:
$xmlDoc = new DOMDocument();
$xmlDoc->load("http://www.bnr.ro/nbrfxrates.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
if($item->nodeName == 'Body')
foreach ($item->childNodes AS $body_item)
{
if($body_item->nodeName == 'Cube')
foreach ($body_item->childNodes AS $cube_item)
{
print " - ".$cube_item->nodeName . " : ".$cube_item->getAttribute("currency")." = ". $cube_item->nodeValue . "<br>";
}
}
}
If i remove the getAttribute part the script runs smoothly, but adding it causes it to return error 500.
The xml is available at the address if you want to check it out or something.
Once I activated error reporting I found the error to be: Object of class DOMText could not be converted to string
The problem is that
childNodesis supplying both regular and text nodes. You can only callgetAttribute()on the regular Element nodes (type 1). Check first that they are not text nodes before executing yourprint:If in your
foreachloop you were to check thenodeTypeof each of thechildNodes, you would most likely see something similar to an alternating3 1 3 1 3 1for the whitespace text and regular element nodes, when you only really want the element nodes (1)MDN has a reference list of DOM node types.
Incidentally, a quick verification of the fix with your full code produces: