simplexml_load_string获取属性

时间:2017-05-14 16:27:27

标签: php xml xml-parsing simplexml-load-string

源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
        )

)

如何让它返回attribute idname的标签?

3 个答案:

答案 0 :(得分:0)

Try this code snippet here

import boto3
client = boto3.client('cloudwatch')

response = client.describe_alarms()

names = [[alarm['AlarmName'] for alarm in response['MetricAlarms']]]
disable_response = client.disable_alarm_actions(names)

<强>输出:

<?php
ini_set('display_errors', 1);
$string=' <attributeGroup id="999" name="Information">
                <attribute id="123" name="Manufacturer">Apple</attribute>
                <attribute id="456" name="Model">iPhone</attribute>  
   </attributeGroup>
';

$xml = simplexml_load_string($string);
$result=array();
foreach($xml->xpath("//attribute") as $attr)
{
    $result[(string)$attr->attributes()->id]= (string) $attr->attributes()->name;
}
print_r($result);

答案 1 :(得分:0)

您可以使用attributes属性访问它:

$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
}

答案 2 :(得分:0)

在PHP手册中非常清楚地显示了许多过于复杂的答案:http://php.net/manual/en/simplexml.examples-basic.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);
}