我有以下类型的XML结构:
<catalog xmlns="http://www.namespace.com">
<product product-id="test-product">
<page-attributes>
<page-title xml:lang="en">test</page-title>
<page-title xml:lang="de">test2</page-title>
</page-attributes>
</product>
</catalog>我使用以下方法获取该产品及其page-title元素:
$xml->registerXPathNamespace('ns', $xml->getNamespaces()[""]);
$xpath = '//ns:product[@product-id="test-product"]';
$product = $xml->xpath($xpath)[0];
foreach ($product->{'page-attributes'}->{'page-title'} as $title) {
var_dump($title);
var_dump($title->{"@attributes"});
var_dump($title->attributes());
}但我只得到:
object(SimpleXMLElement)#4 (0) {
}
object(SimpleXMLElement)#6 (0) {
}
object(SimpleXMLElement)#6 (0) {
}
object(SimpleXMLElement)#6 (0) {
}
object(SimpleXMLElement)#4 (0) {
}
object(SimpleXMLElement)#4 (0) {
}如何获得page-title元素(test,test2)的值?另外,我如何获得属性?属性前面有xml:。这是否意味着属性仅位于它们自己的命名空间中?
发布于 2015-01-28 16:47:06
您的代码有两处问题:
SimpleXMLElement的值,则需要将其转换为string。xml:属性值,则需要指定名称空间lang。您的代码应该如下所示:
$xml->registerXPathNamespace('ns', $xml->getNamespaces()[""]);
$xpath = '//ns:product[@product-id="test-product"]';
$product = $xml->xpath($xpath)[0];
foreach ($product->{'page-attributes'}->{'page-title'} as $title) {
var_dump((string) $title);
var_dump((string) $title->attributes('xml', TRUE)['lang']);
}输出:
string(4) "test"
string(2) "en"
string(5) "test2"
string(2) "de"关于字符串转换。请注意,如果要尝试执行以下操作:
echo "Title: $title";您不必显式转换为string,因为SimpleXMLElement支持__toString()方法,并且PHP将自动将其转换为字符串--在这样的字符串上下文中。
var_dump()不能假定字符串上下文,因此它输出变量SimpleXMLElement的“真实”类型。
https://stackoverflow.com/questions/28197243
复制相似问题