Php SimpleXML在1个元素中包含更多标记

Php SimpleXML在1个元素中包含更多标记,php,xml,simplexml,Php,Xml,Simplexml,嘿,伙计们,我想解析一些xml,但我不知道如何从1个元素中获得相同的标记 我想分析一下: <profile> <name>john</name> <lang>english</lang> <lang>dutch</lang> </profile> 厕所 英语 荷兰的 所以我想解析john所说的语言。我该怎么做呢?在使用SimpleXML将元素节点拉入后,可以在元素节点上运行fo

嘿,伙计们,我想解析一些xml,但我不知道如何从1个元素中获得相同的标记

我想分析一下:

<profile>
   <name>john</name>
   <lang>english</lang>
   <lang>dutch</lang>
</profile>

厕所
英语
荷兰的

所以我想解析john所说的语言。我该怎么做呢?

在使用SimpleXML将元素节点拉入后,可以在元素节点上运行
foreach
循环,如下所示:

$profile->lang[0]
$profile->lang[1]
$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.
$xProfile=simplexml\u load\u字符串(“…”);
$sName='john';
$aLang=$xProfile->xpath(“/profile/name[text()=””)“$sName.”]/lang”);
//现在$aLang将是一个lang*节点数组*(John为2)。因为他们
//节点是否仍然可以使用它们执行SimpleXML“工作”,即。
//$aLang[0]->attributes()--哪个是空对象
//甚至
$sPerson=(字符串)$aLang[0]->xpath('preference-sibling::name');
//当然你已经知道了。。。但这只是为了展示你能做什么
//使用SimpleXml节点。