如何从一个父元素的多个 XML 子元素中获取所有值

我有供应商提供的 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>

它工作得很好,但 throw 的唯一第一个组合


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

但我还想要这个 ID 的其他组合


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

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

在哪里寻找解决方案?


吃鸡游戏
浏览 110回答 1
1回答

呼唤远方

简单地添加一个 foreach $product->combinations->combination。例如:$xml = simplexml_load_file('export.xml');$result = $xml->xpath("//product");$array= array();&nbsp; &nbsp; foreach ($result as $product) {&nbsp; &nbsp; &nbsp; &nbsp; $id = (string)$product->id;&nbsp; &nbsp; &nbsp; &nbsp; $code = (string)$product->code;&nbsp; &nbsp; &nbsp; &nbsp; foreach( $product->combinations->combination as $combination ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $ean = (string)$combination->ean;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $quantity = (string)$combination->quantity;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print 'ID:' .$id. ' CODE:' .$code. ' EAN: '.$ean.' - <b>'.$quantity.'</b> szt.<br />';&nbsp; &nbsp; &nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP