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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料