如何在PHP中索引XML元素? [英] How to index XML elements in PHP?
问题描述
我是PHP和XML的虚拟人物,所以请耐心等待我的问题看起来很笨拙。
I am dummy to PHP and XML, so please be patient if my question seems dumb.
我想知道如何索引XML元素,以便我可以访问它们我打算把它们放在一个阵列中。但是,我不知道如何获取返回的元素数量。
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.
以下是代码:
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 />";
}
?>
当我执行 echo count($ names);
它返回 1
,这显然不是元素的数量。请帮助。
When I do the echo count($names);
it returns 1
, which is obviously not the number of elements. Please help.
推荐答案
查看的返回值getElementsByTagName
,这将是 DOMNodeList 。
同样对于您的问题,您可以执行以下操作:
Also for your problem you could do something like:
$names = array();
foreach ($dom->getElementsByTagName("name") as $nameNode) {
$names[] = $nameNode->nodeValue;
}
您不必真正检查<$ c $的返回值c> getElementsByTagName ,因为它将会是一个DOMNodeList。这样你可以直接在foreach-loop中使用它来分配不需要的变量。
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.
你需要检查的是$ code> $ name的大小,循环后。
What you have to check, is the size of $names
, after the loop.
这篇关于如何在PHP中索引XML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!