【问题标题】:Xpath get specific attribute valuesXpath 获取特定属性值
【发布时间】:2012-09-06 08:45:05
【问题描述】:

我得到了这个 XML:

            <shipping_line>
                <article id="960382" quantity="500" />
                <article id="960560" quantity="150" />
                <article id="960426" quantity="250" />
                <article id="1177" quantity="100" >
                    <product>5500070000126273</product>
                    <product>5500070000126264</product>
                    <product>5500070000126255</product>
                    <product>5500070000126246</product>
                    <product>5500070000126237</product>
                </article>
            </shipping_line>

然后我像这样访问文章元素atributes id 和quantity

$atrs = $xml->xpath('//article[not(node())]/@quantity | //article[not(node())]/@id');

现在我想访问我创建的 foreach 的 2 个值,如下所示:

            foreach ($atrs as $id => $val ) {

                error_log(print_r($val , true));

            }

我的错误日志显示:

 SimpleXMLElement Object\n(\n    [@attributes] => Array\n        (\n            [id] => 960382\n        )\n\n)\n
 SimpleXMLElement Object\n(\n    [@attributes] => Array\n        (\n            [quantity] => 500\n        )\n\n)\n
 SimpleXMLElement Object\n(\n    [@attributes] => Array\n        (\n            [id] => 960560\n        )\n\n)\n
 SimpleXMLElement Object\n(\n    [@attributes] => Array\n        (\n            [quantity] => 150\n        )\n\n)\n
 SimpleXMLElement Object\n(\n    [@attributes] => Array\n        (\n            [id] => 960426\n        )\n\n)\n
 SimpleXMLElement Object\n(\n    [@attributes] => Array\n        (\n            [quantity] => 250\n        )\n\n)\n

我怎样才能访问这 2 个值,以便我可以使用类似的函数 someFunctionUsing2Values($article_no , $quantity)

【问题讨论】:

    标签: php arrays xml xpath


    【解决方案1】:

    我会这样做:

    $xml = new SimpleXMLElement('
    <shipping_line>
        <article id="960382" quantity="500" />
        <article id="960560" quantity="150" />
        <article id="960426" quantity="250" />
        <article id="1177" quantity="100" >
            <product>5500070000126273</product>
            <product>5500070000126264</product>
            <product>5500070000126255</product>
            <product>5500070000126246</product>
            <product>5500070000126237</product>
        </article>
    </shipping_line>');
    
    $nodes = $xml->xpath('//article[not(node())]');
    foreach ($nodes as $node)
    {
        fn($node['id'], $node['quantity']);
    }
    
    function fn($id, $quantity)
    {
        echo "$id -> $quantity<br>";
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-14
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多