【问题标题】:simplexml_load_string get attributessimplexml_load_string 获取属性
【发布时间】:2017-05-14 16:27:26
【问题描述】:

源 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 的标签?

【问题讨论】:

    标签: php xml xml-parsing simplexml


    【解决方案1】:

    您可以使用 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
    }
    

    【讨论】:

    • 谢谢。那行得通,但是我怎样才能在同一个数组中获取文本值?所以它会显示 id、name 和 text 值。
    【解决方案2】:

    Try this code snippet here

    <?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);
    

    输出:

    Array
    (
        [123] => Manufacturer
        [456] => Model
    )
    

    【讨论】:

      【解决方案3】:

      这里的 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);
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-30
        • 1970-01-01
        • 1970-01-01
        • 2015-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        相关资源
        最近更新 更多