嘿伙计们,我想解析一些 xml,但我不知道如何从 1 个元素中获取相同的标签。
我想解析这个:
<profile>
<name>john</name>
<lang>english</lang>
<lang>dutch</lang>
</profile>
所以我想解析约翰说的语言。我怎样才能做到这一点 ?
$profile->lang[0]
$profile->lang[1]
foreach
使用 SimpleXML 将其拉入后,您可以在元素节点上运行一个循环,如下所示:
$xml_profiles = simplexml_load_file($file_profiles);
foreach($xml_profiles->profile as $profile)
{ //-- first foreach pulls out each profile node
foreach($profile->lang as $lang_spoken)
{ //-- will pull out each lang node into a variable called $lang_spoken
echo $lang_spoken;
}
}
这样做的好处是能够lang
为每个配置文件元素处理您可能拥有或不拥有的任意数量的元素。
将重复的 XML 节点想象成一个数组。
正如其他人指出的那样,您可以使用括号语法访问子节点
myXML->childNode[childIndex]
作为旁注,这就是 RSS 提要的工作方式。你会注意到多个
<item>
</item>
<item>
</item>
<item>
</item>
RSS XML 标签内的标签。RSS 阅读器每天都通过将列表视为元素数组来处理这个问题。
可以循环播放。
您还可以使用 XPath 来收集特定元素的数组,例如
$xProfile = simplexml_load_string("<profile>...</profile>");
$sName = 'john';
$aLang = $xProfile->xpath("/profile/name[text()='".$sName."']/lang");
// Now $aLang will be an array of lang *nodes* (2 for John). Because they
// are nodes you can still do SimpleXML "stuff" with them i.e.
// $aLang[0]->attributes(); --which is an empty object
// or even
$sPerson = (string)$aLang[0]->xpath('preceding-sibling::name');
// of course you already know this... but this was just to show what you can do
// with the SimpleXml node.