Baltazar
Baltazar

Reputation: 67

Get the specific identifier in xml code with php

Good day, I'm trying to get a specific value of an XML file in this example I need to get a productidentifier in each product that has the tag <b221> set to 03 something like this:

<productidentifier><b221>03</b221><b244>9783672461027</b244></productidentifier>

where I can get then the <b244> tag to store the EAN.

The problem is that specific items have sometimes more then one productidentifier for example:

<productidentifier><b221>02</b221><b244>3672461024</b244></productidentifier>
<productidentifier><b221>03</b221><b244>9783672461027</b244></productidentifier>

So far I tried to use:

    foreach ($xml->product as $item) {
            $item->productidentifier->b221
    }

Which will always return me the first productidenfitier in the list

    foreach ($xml->product as $item) {
                $identifier = $item->productidentifier->xpath('//productidentifier');
                dd($identifier);
    }

Which returns me all the product identifiers in the list: https://i.sstatic.net/mq0NE.png

How to do it?

Thank you for reading.

Upvotes: 2

Views: 52

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

You would need to extend your XPath expression to include a check that the <b221> element is 03. This code searches for these and outputs the <b244> value

foreach  ( $xml->xpath('//productidentifier[b221="03"]') as $product )    {
    echo $product->b244.PHP_EOL;
}

Upvotes: 1

Related Questions