xml到csv转换php

时间:2015-06-04 22:30:17

标签: php xml csv

大家好我想知道是否有快速获取xml系列 - >系列['代码']并查看它是否等于products-> product->系列['代码']如果相等,则将产品 - >系列['代码']替换为family-> family [' title']。

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

1 个答案:

答案 0 :(得分:1)

if ((string)$xml->products->product->family['code'] == (string)$xml->families->family['code']) {
     $xml->products->product->family['code']= $xml->families->family['title'];
     }
由于更新了问题,

更新

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的内存使用问题,请将其设为anoter

$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']];
}