SimpleXML 不返回属性

SimpleXML not returning attributes

我正在尝试显示 xml 文件中所有项目的属性。我有以下 xml 文件:

<OPupdate>
    <Version>Testing</Version>
    <VersionNumber>1.0</VersionNumber>
    <GenerationDate>2015-04-24T11:21:53.013</GenerationDate>
    <Product>
        <ProductID>P001</ProductID>
        <ProductAttribute>
            <Attribute ID="1" description="Att1" lang="en-GB" type="string" displaysequence="0">A</Attribute>
            <Attribute ID="2" description="Att2" lang="en-GB" type="string" displaysequence="0">B</Attribute>
            <Attribute ID="3" description="Att3" lang="en-GB" type="string" displaysequence="0">B</Attribute>
        </ProductAttribute>
    </Product>
</OPupdate>

php中的这个:

$xml = simplexml_load_file('test.xml');
foreach( $xml->Product as $product ) {
    foreach ( $product->ProductAttribute as $attribute ) {
        foreach( $attribute->attributes() as $key => $value ) {
            printf( '1<p><strong>%s:</strong> %s</p>', $key, $value );
        }
    }
}

但这并没有输出任何东西。谁能告诉我这里出了什么问题?

试试这个

$xml = simplexml_load_file('test.xml');
foreach( $xml->Product as $product ) {
    foreach ( $product->ProductAttribute as $attribute ) {
      echo  $attribute['ID'];
    }
}

实际上 $attribute 将被视为数组或其属性。

更新评论:
foreach($pattribute->Attribute as $attribute ){
foreach($attribute->attributes() as $key=>$value)
你错过了一个循环,
感谢您指出。
旧:
属性是一个数组
使用:foreach( $attribute as $key => $value ) 而不是 foreach( $attribute->attributes() as $key => $value )

它适用于此:

foreach( $xml->Product as $product ) {
    foreach ( $product->ProductAttribute as $attribute ) {
        foreach( $attribute->children() as $att) {
            echo $att['description'];
        }
    }
}

编辑:

foreach( $xml->Product as $product ) {
    foreach ( $product->ProductAttribute->Attribute as $attribute ) {
        $column = $attribute['description']->__toString(); // the description attribute of the Attribute node
        $value = $attribute->__toString(); // the actual value of the Attribute item
    }
}

您在这里的混淆是术语之一 - 在下文中,"Foo" 是一个 元素 ,而 "bar" 是一个 属性:

<Foo bar="value">content</Foo>

在您的示例 XML 中,有一个 元素 其名称恰好是 "Attribute":

<Attribute ID="1" description="Att1" lang="en-GB" type="string" displaysequence="0">A</Attribute>

它有几个属性,例如"ID"和"description",以及一些内容"A"。

因此,要访问它,您需要使用与其他元素完全相同的语法,"Product" 和 "ProductAttribute":

foreach ( $attribute->Attribute as $something ) {
     echo (string)$something; // content of the element: 'A'
     echo (string)$something['ID']; // value of the 'ID' attribute: '1'
}

假设总是只有一个 "ProductAttribute",就像你的例子一样,你可以这样做,这样可读性更好:

foreach ( $product->ProductAttribute->Attribute as $attribute ) {
     echo (string)$attribute; // A
     echo (string)$attribute['ID']; // 1
}

您找到的 attributes() 方法将允许您遍历元素的属性:

freach ( $attribute->attributes() as $key => $value ) {
     echo "$key: $value\n";
}

这将为第一个 "Attribute" 元素生成以下键和值列表:

ID: 1
description: Att1
lang: en-GB
type: string
displaysequence: 0

然后是其他 "Attribute" 元素的类似列表。

都怪英语的不精确,谁设计了这个XML结构!