【问题标题】:xml to csv conversion phpxml到csv转换php
【发布时间】:2015-06-04 22:30:16
【问题描述】:

大家好,我想知道是否有一种快速的方法来获取 xml family->family['code'] 并查看它是否等于 products->product->family['code'] 以及是否相等用family->family['title']替换product->family['code']。

xml 代码:

<products>
  <product code="002732" title="Bluetooth Headset " price="2.00" available="true">
    <family code="03" />            
      <description>        
        <lang-en><![CDATA[This product reproduces the original artwork]]></lang-en>
      </description>
  </product>
  <product code="004587" title="Headset " price="5.00" available="true">
     <family code="05" />            
       <description>        
         <lang-en><![CDATA[something]]></lang-en>
       </description>
  </product>
</products>
<families>
  <family code="03" title="Mobile Accessories"></family>
  <family code="05" title="Accessories"></family>
</families>    

我的php代码:

$fileName = 'demo.csv';
$xml=simplexml_load_file("demo.xml") or die("Error: Cannot create object");
ob_start();
echo 'Product code;Language;Product name;Price;Status;Detailed image;Description;Category'."\n";

foreach($xml->products->product as $child){ 
  echo $child['code'].';en;';
  echo $child['title'].';';
  echo $child['price'].';';
  echo $child['available'].';';    
  echo $child->image['src'].';';
  echo $child->description->{'lang-en'}."\n";;       
}

$htmlStr = ob_get_contents();
ob_end_clean();      
file_put_contents($fileName, $htmlStr);

【问题讨论】:

    标签: php xml csv


    【解决方案1】:
    if ((string)$xml->products->product->family['code'] == (string)$xml->families->family['code']) {
         $xml->products->product->family['code']= $xml->families->family['title'];
         }
    

    UPDATE由于问题的更新

    foreach ($xml->products->product as $child) {
        echo $child->family['code'];
        $title = $xml->xpath("//families/family[@code=".$child->family['code']."]");
        if ($title) $child->family['code'] = (string)$title[0]['title'];
    }
    echo $xml->saveXML();
    

    UPDATE2如果xpath的内存使用问题,改成其他的

    $codes = array();
    foreach ($xml->families->family as $family)   
       $codes[(string)$family['code']] = (string) $family['title'];
    
    foreach ($xml->products->product as $child) {
        if (isset($codes[(string)$child->family['code']])) 
            $child->family['code'] = $codes[(string)$child->family['code']];
    }
    

    【讨论】:

    • 抱歉这对我不起作用,因为我想遍历 xml 文件中的 2 个不同层并比较两者。这是我的错误,我只发布了一个产品和一个类别。
    • 它在小 xml 中工作,但在大 xml 中它只会产生最大执行错误。我将计时器设置为 300 但仍然相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 2017-12-14
    • 2013-06-10
    相关资源
    最近更新 更多