我得到了这个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)
答案 0 :(得分: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>";
}