JoeDoe
JoeDoe

Reputation: 47

Select item by attribute using simplexml

I want to select only specified warehouse to update stock. I.E. I want only 99, but every item has different number of warehouses so the code below only works in 99 warehouse in in 3 row:

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

Here's sample 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>

and print_r($this_product->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
)

Upvotes: 0

Views: 76

Answers (1)

ThW
ThW

Reputation: 19492

To fetch a part of an DOM use Xpath expressions. SimpleXMLElement::xpath() provides access to it:

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

The DOM extension itself has the DOMXpath class for it:

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

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

Upvotes: 1

Related Questions