The problem is that childNodes
is supplying both regular and text nodes. You can only call getAttribute()
on the regular Element nodes (type 1). Check first that they are not text nodes before executing your print
:
foreach ($body_item->childNodes AS $cube_item)
{
// Only attempt to print the regular DOM elements
if ($cube_item->nodeType == 1)
{
print " - ".$cube_item->nodeName . " : ".$cube_item->getAttribute("currency")." = ". $cube_item->nodeValue . "<br>";
}
}
If in your foreach
loop you were to check the nodeType
of each of the childNodes
, you would most likely see something similar to an alternating 3 1 3 1 3 1
for 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:
- Rate : AED = 0.9514<br>
- Rate : AUD = 3.6518<br>
- Rate : BGN = 2.3169<br>
- Rate : BRL = 1.6787<br>
- Rate : CAD = 3.5182<br>
- Rate : CHF = 3.7628<br>
- Rate : CNY = 0.5613<br>
- Rate : CZK = 0.1790<br>
- Rate : DKK = 0.6076<br>
- Rate : EGP = 0.5726<br>
- Rate : EUR = 4.5313<br>
- Rate : GBP = 5.5990<br>
- Rate : HUF = 1.6075<br>
- Rate : INR = 0.0627<br>
- Rate : JPY = 4.2601<br>
- Rate : KRW = 0.3217<br>
- Rate : MDL = 0.2836<br>
- Rate : MXN = 0.2692<br>
- Rate : NOK = 0.6169<br>
- Rate : NZD = 2.8782<br>
- Rate : PLN = 1.1019<br>
- Rate : RSD = 0.0405<br>
- Rate : RUB = 0.1127<br>
- Rate : SEK = 0.5268<br>
- Rate : TRY = 1.9469<br>
- Rate : UAH = 0.4288<br>
- Rate : USD = 3.4950<br>
- Rate : XAU = 196.3192<br>
- Rate : XDR = 5.3606<br>
- Rate : ZAR = 0.3937<br>