-1

我得到了这个 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>

我访问文章元素atributesid,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

我如何访问这两个值,以便我可以使用类似的函数 someFunctionUsing2Values($article_no , $quantity)

4

1 回答 1

2

这是我的做法:

$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>";
}
于 2012-09-06T08:55:33.987 回答