PipBoy2000
PipBoy2000

Reputation: 440

How to get all values from multiple XML child element for one parent element

I have XML file from my supplier. I want to read data from that file. My read.php file contains:

$xml = simplexml_load_file('export.xml');
$result = $xml->xpath("//product");
$array= array();
    foreach ($result as $product) {
        $id = (string)$product->id;
        $code = (string)$product->code;
        $ean = (string)$product->combinations->combination->ean;
        $quantity = (string)$product->combinations->combination->quantity;
        print_r('ID:' .$id. ' CODE:' .$code. ' EAN: '.$ean.' - <b>'.$quantity.'</b> szt.<br />');
}

XML looks like

<product>
  <id>684</id>
  <code>113</code>
    <combinations>
        <combination>
            <ean>111</ean>
            <quantity>0</quantity>
        </combination>
        <combination>
            <ean>222</ean>
            <quantity>5</quantity>
        </combination>
        <combination>
            <ean>333</ean>
            <quantity>2</quantity>
        </combination>
    </combinations>
</product>

It work quite fine but throw's only first combination

ID:684 CODE:113 EAN: 111 - 0 szt.

but i want also other combinations of this ID

ID:684 CODE:113 EAN: 222 - 5 szt.
ID:684 CODE:113 EAN: 333 - 2 szt.

Where to find solution?

Upvotes: 0

Views: 212

Answers (1)

Stefano Pascazi
Stefano Pascazi

Reputation: 389

Simple add a foreach $product->combinations->combination.

For Example:

$xml = simplexml_load_file('export.xml');
$result = $xml->xpath("//product");
$array= array();
    foreach ($result as $product) {
        $id = (string)$product->id;
        $code = (string)$product->code;
        foreach( $product->combinations->combination as $combination ){

            $ean = (string)$combination->ean;
            $quantity = (string)$combination->quantity;
            print 'ID:' .$id. ' CODE:' .$code. ' EAN: '.$ean.' - <b>'.$quantity.'</b> szt.<br />';
        }
}

Upvotes: 1

Related Questions