如何使用PHP XMLREADER读取XML文件



我有这个XML:

<DATASET>
<ITEM>
<NAME>name product</NAME>
<SELL>0</SELL>
<PARAM>
<PARAM_NAME>material</PARAM_NAME>
<VAL>polyester</VAL>
<PERCENTAGE>96%</PERCENTAGE>
</PARAM>
<PARAM>
<PARAM_NAME>material</PARAM_NAME>
<VAL>elastan</VAL>
<PERCENTAGE>4%</PERCENTAGE>
</PARAM>
</ITEM>
</DATASET>

我需要有关如何将数据(从标签 PARAM(获取到字段中的建议:

$array[0][聚酯]=96%;$array[1][弹性蛋白]=4%;

<?php
$xmlstr = "<DATASET>
<ITEM>
<NAME>name product</NAME>
<SELL>0</SELL>
<PARAM>
<PARAM_NAME>material</PARAM_NAME>
<VAL>polyester</VAL>
<PERCENTAGE>96%</PERCENTAGE>
</PARAM>
<PARAM>
<PARAM_NAME>material</PARAM_NAME>
<VAL>elastan</VAL>
<PERCENTAGE>4%</PERCENTAGE>
</PARAM>
</ITEM>
</DATASET>";
   $xml_reader = new XMLReader();
   $xml_reader->xml($xmlstr);
   while ($xml_reader->read() && $xml_reader->name != 'PARAM');
   $array = [];
   $i = 0;
   while ($xml_reader->name == 'PARAM') {
     // load the current xml element into simplexml
     $param = new SimpleXMLElement($xml_reader->readOuterXML());
     // now you can use your simpleXML object ($xml)
     $array[$i] = array( (string)$param->VAL => (string)$param->PERCENTAGE );
     // move the pointer to the next param
     $xml_reader->next('PARAM');
     $i++;
   }
   // don’t forget to close the file
   $xml_reader->close();
   print_r($array);
?>

结果:

Array
(
    [0] => Array
        (
            [polyester] => 96%
        )
    [1] => Array
        (
            [elastan] => 4%
        )
)

看到它运行在: http://sandbox.onlinephpfunctions.com/code/c7066412afc321e82bef1da570ebc54487c79fab

最新更新