Php simplexml\u加载\u字符串获取属性

Php simplexml\u加载\u字符串获取属性,php,xml,xml-parsing,simplexml,Php,Xml,Xml Parsing,Simplexml,源XML是: <attributeGroup id="999" name="Information"> <attribute id="123" name="Manufacturer">Apple</attribute> <attribute id="456" name="Model">iPhone</attribute> </attributeGroup> $xml = simplexml_load_str

源XML是:

<attributeGroup id="999" name="Information">
   <attribute id="123" name="Manufacturer">Apple</attribute>
   <attribute id="456" name="Model">iPhone</attribute>  
</attributeGroup>
$xml = simplexml_load_string($xml);
print_r($xml);
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 999
            [name] => Information
        )

    [attribute] => Array
        (
            [0] => Apple
            [1] => iPhone
        )

)
Array
(
    [123] => Manufacturer
    [456] => Model
)
输出:

<attributeGroup id="999" name="Information">
   <attribute id="123" name="Manufacturer">Apple</attribute>
   <attribute id="456" name="Model">iPhone</attribute>  
</attributeGroup>
$xml = simplexml_load_string($xml);
print_r($xml);
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 999
            [name] => Information
        )

    [attribute] => Array
        (
            [0] => Apple
            [1] => iPhone
        )

)
Array
(
    [123] => Manufacturer
    [456] => Model
)
如何让它返回
属性id
名称的标签?


您可以使用“属性”属性按如下方式访问它:

$x = simplexml_load_string($xml);
$g = $x->attributeGroup;
foreach($g->xpath("//attribute") as $attr){
    var_dump((string)$attr->attributes()->id);
    var_dump((string)$attr->attributes()->name);
    var_dump((string)$attr); // for text value
}

PHP手册中清楚地显示了许多过于复杂的答案:

您只需执行以下操作:

$sx = simplexml_load_string($xml);
// $sx is the outer tag of your XML; in your example <attributeGroup>
// Access child tags with ->
foreach($sx->attribute as $attr){
    // Access attributes with ['...']
    var_dump((string)$attr['id']);
    // Access text and CDATA content with (string)
    var_dump((string)$attr);
}
$sx=simplexml\u load\u字符串($xml);
//$sx是XML的外部标记;在你的例子中
//使用->
foreach($sx->属性为$attr){
//使用“…”访问属性
变量转储((字符串)$attr['id']);
//使用(字符串)访问文本和CDATA内容
变量转储((字符串)$attr);
}

谢谢。这是可行的,但是如何在同一个数组中获得文本值呢?因此,它将显示id、名称和文本值。