Reputation: 10952
I am dummy to PHP and XML, so please be patient if my question seems dumb.
I want to know how to index the XML elements so that I can access them. I am planning to put them into an array. However, I don't know how to get the number of elements returned.
Here are the codes:
exer.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<actionstars>
<name>Jean Claude Van Damme</name>
<name>Scott Adkins</name>
<name>Michael Jai White</name>
<name>Dolph Lundgren</name>
<name>Tom Cruise</name>
<name>Michael Worth</name>
</actionstars>
index.php
<?php
$dom = new DomDocument();
$dom->load("exer.xml");
$names = $dom->getElementsByTagName("name");
echo count($names);
foreach($names as $name) {
print $name->textContent . "<br />";
}
?>
When I do the echo count($names);
it returns 1
, which is obviously not the number of elements. Please help.
Upvotes: 1
Views: 1120
Reputation: 54659
Have a look at the return value of getElementsByTagName
, which will be a DOMNodeList.
Also for your problem you could do something like:
$names = array();
foreach ($dom->getElementsByTagName("name") as $nameNode) {
$names[] = $nameNode->nodeValue;
}
You don't have to actually check the return value of getElementsByTagName
, for it will allways be a DOMNodeList. This way you can use it directly in the foreach-loop whithout assigning unneeded variables.
What you have to check, is the size of $names
, after the loop.
Upvotes: 1