使用simplexml按属性选择项目

时间:2017-08-01 16:13:22

标签: php xml attributes simplexml

我想只选择指定的仓库来更新库存。 I.E.我只想要99,但是每个项目都有不同数量的仓库,所以下面的代码只能在99行仓库中进行3行:

$quantity_calc = $this_product->stock[2];

此处的示例xml:

<product sku="123546" supplier="BOSCH" price="1.71">
<stock warehouse="SAND">2.00</stock>
<stock warehouse="44">2.00</stock>
<stock warehouse="55">4.00</stock>
<stock warehouse="77">2.00</stock>
<stock warehouse="88">2.00</stock>
<stock warehouse="97">2.00</stock>
<stock warehouse="99">2.00</stock>
<stock warehouse="33">2.00</stock>
</product>

和print_r($ this_product-&gt; stock);

[@attributes] => Array
        (
            [warehouse] => SAND
        )

    [0] => 2.00
    [1] => 2.00
    [2] => 4.00
    [3] => 2.00
    [4] => 2.00
    [5] => 2.00
    [6] => 2.00
    [7] => 2.00
)

1 个答案:

答案 0 :(得分:1)

要获取DOM的一部分,请使用Xpath表达式。 SimpleXMLElement::xpath()可以访问它:

$product = new SimpleXMLElement($xml);
var_dump(
  (string)$product->xpath('//stock[@warehouse=99]')[0]
);

DOM扩展本身具有DOMXpath类:

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);

var_dump(
  $xpath->evaluate('string(//stock[@warehouse=99])')
);