PHP解析<cpe-23:cpe23-item name =“...”>?</cpe-23:cpe23-item>

时间:2015-01-18 17:13:56

标签: php xml simplexml

我用SimpleXML PHP解析了这个标签。

这是我的档案:

<cpe-item name="cpe:/a:%240.99_kindle_books_project:%240.99_kindle_books:6::">
    <cpe-23:cpe23-item name="cpe:2.3:a:\*:*:*:*:*:*:*:*:*:*"/>
</cpe-item>

我想在cpe-23上解析名称内容:cpe23-item。

这是我现在的代码:

foreach ($xml->{'cpe-item'} as $cpe) {
  echo $cpe->children('cpe-23', TRUE) // This is the line I have to modify
}

1 个答案:

答案 0 :(得分:0)

$cpe->children('cpe-23', TRUE)返回名称空间中前缀为cpe-23:的所有子项。

要访问某个特定的孩子,最简单的方法是按名称引用它,在本例中为->cpe23-item,因为该元素为<cpe23-item ...>。但是,这会混淆PHP的解析器,因为-通常意味着“减”;您可以使用{}围绕名称来避免这种情况,例如->{cpe23-item}

要获取该元素的属性,通常会使用数组访问,例如['name']。但是,XML命名空间的怪癖意味着此处的name=属性位于 no namespace 中,因此您必须使用->attributes()函数“离开”cpe-23命名空间您通过->children()来电“输入”了->attributes(null)->name

总而言之,你有:

echo $cpe->children('cpe-23', TRUE)->{cpe23-item}->attributes(null)->name;