SimpleXML 命名空间属性和值是否为空?

SimpleXML namespaced attributes and value is empty?

我有以下类型的 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 元素(testtest2)的值?另外我如何获得属性?属性前面有xml:。这是否意味着只有属性在它们自己的命名空间中?

您的代码有两处错误:

  • 正如@MichaelBerkowski 提到的,如果您尝试检索它的值,则需要将 SimpleXMLElement 转换为 string

  • 如果您尝试检索 lang 属性的值,则需要指定命名空间 xml:

您的代码应如下所示:

$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() 不能假定字符串上下文,因此它输出变量的 "real" 类型:SimpleXMLElement.