doupu1957 2013-12-02 09:50
浏览 45
已采纳

PHP - 解析XML一行记录

I have the following issue. I have an XML file with the following structure:

<?xml version="1.0" encoding="utf-8"?>
<Stocproduse>
<record ProdusId="1622" Stoc="11.00"/>
<record ProdusId="1632" Stoc="11.00"/>
</Stocproduse>

I'm trying to use the following PHP script to insert the data into a csv file, but it doesn't work:

$filexml='/var/www/html/site.com/Stoc_produse.xml';
$xml = simplexml_load_file($filexml);
$f = fopen('/var/www/html/site.com/stoc_produse.csv', 'w');
foreach($xml->record as $record){
$values = array("ProdusId" => $record->ProdusId, "Stoc" => $record->Stoc);
    fputcsv($f, $values,','," ");
}
fclose($f);

However, if I convert the XML structure in the following way it works:

<?xml version="1.0" encoding="utf-8"?>
<Stocproduse>
<record>
<ProdusId>1622</ProdusId>
<Stoc>11.00</Stoc>
</record>
<record>
<ProdusId>1623</ProdusId>
<Stoc>11.00</Stoc>
</record>
</Stocproduse>

Does anyone have any idea what modifications I should make to the php script in order for it to work with the first xml structure? Any help will be greatly appreciated.

Thank you.

  • 写回答

3条回答 默认 最新

  • doutou1922 2013-12-02 10:11
    关注

    You can access XML node elements in one of two ways:

    1. The aforementioned PHP SimpleXmlElement Attributes function;
    2. Direct access using [''].

    Since there are a lot of examples of the 1st method I leave you with a working example of the 2nd one:

    <?php
    $xml = <<<XML
    <?xml version="1.0" encoding="utf-8"?>
    <Stocproduse>
        <record ProdusId="1622" Stoc="11.00"/>
        <record ProdusId="1632" Stoc="11.00"/>
    </Stocproduse>
    XML;
    
    $sxe = new SimpleXMLElement($xml);
    
    foreach($sxe->record as $record){
        $values = array("ProdusId" => $record['ProdusId'], "Stoc" => $record['Stoc']);
    }
    
    print_r($values);
    

    Output:

    Array
    (
        [ProdusId] => SimpleXMLElement Object
        (
            [0] => 1632
        )
    
        [Stoc] => SimpleXMLElement Object
        (
            [0] => 11.00
        )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加