Как получить все значения из нескольких дочерних элементов XML для одного родительского элемента - PullRequest
0 голосов
/ 23 сентября 2019

У меня есть XML-файл от моего поставщика.Я хочу прочитать данные из этого файла.Мой файл read.php содержит:

$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 выглядит как

<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>

Он работает довольно хорошо, но только первая комбинация броска

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

, но я хочу такжедругие комбинации этого идентификатора

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

Где найти решение?

1 Ответ

1 голос
/ 23 сентября 2019

Просто добавьте foreach $ product-> комбинации-> комбинации.

Например:

$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 />';
        }
}
...