如何访问一个简单xml对象的键/属性


How do I get access to keys/attributes of a simple-xml object

我有一个xml对象,如下所示:

<search typ="car" sub="all" out="test" epc="2" tsc="1" rcc="111" tpc="111" cur="DOL" itc="10">

或者使用var_dump():

object(SimpleXMLElement)[1012]
  public 'search' => 
    object(SimpleXMLElement)[1078]
          public '@attributes' => 
            array (size=9)
              'typ' => string 'car' (length=8)
              'sub' => string 'all' (length=3)
              'out' => string 'test' (length=11)
              'epc' => string '2' (length=1)
              'tsc' => string '1' (length=1)
              'rcc' => string '111' (length=3)
              'tpc' => string '111' (length=3)
              'cur' => string 'DOL' (length=3)
              'itc' => string '10' (length=2)

如何访问xml结的属性?

只需使用->attributes即可访问节点的属性。示例:

$xml = simplexml_load_string($xml_string); // or load_file
echo '<pre>';
print_r($xml->attributes());

单独:

// PHP 5.4 or greater (dereference)
echo $xml->attributes()['typ'];

如手册中的基本用法示例所示,访问属性的标准方法是使用数组访问($element['attributeName']),例如

echo $search['typ'];
$typ = (string)$search['typ'];

请注意,属性是作为对象返回的,因此在将其存储在变量中时,通常需要"强制转换"为字符串(或int等)。

要迭代所有属性,可以使用->attributes()方法,例如

foreach ( $search->attributes() as $name => $value ) {
     echo "$name: $value'n";
     $some_hash[ $name ] = (string)$value;
}

如果您有XML名称空间,也需要attributes()方法,例如`

$sx = simplexml_load_string(
    '<foo xlmns:bar="http://example.com#SOME_XMLNS" bar:becue="yum" />'
);
echo $sx->attributes('http://example.com#SOME_XMLNS')->becue;
// Or, shorter but will break if the XML is generated with different prefixes
echo $sx->attributes('bar', true)->becue;