XML to CSV in PHP

僤鯓⒐⒋嵵緔 提交于 2019-12-11 17:15:34

问题


I am trying to convert XML to CSV with the code below but it will only work if there is only one row. Multiple entries will only display the headers/column names.

This is what my XML looks like:

<Cars>
  <Type>B</Type>
  <Car>
    <Brand>Car1</Brand>
    <Model>M1</Model>
    <Year>2010</Year>
    <Age>9</Age>
    <Desciption>test</Desciption>
  </Car>
</Cars>


<Cars>
  <Type>B</Type>
  <Car>
    <Brand>Car2</Brand>
    <Model>M2</Model>
    <Year>2015</Year>
    <Age>4</Age>
    <Desciption>test</Desciption>
  </Car>
</Cars>

My code:

 $filexml='cars.xml';

  $cname=array();

  $cname[] = 'Brand';
  $cname[] = 'Model';
  $cname[] = 'Year';
  $cname[] = 'Age';
  $cname[] = 'Desciption';


  if (file_exists($filexml)) {
      $xml = simplexml_load_file($filexml); 
      $f = fopen('cars.csv', 'w') or die('Can\'t create .csv file, try again later.');
      fputcsv($f, $cname);

      foreach ($xml->Car as $Car) {
        fputcsv($f, get_object_vars($Car),',','"');
      } 

      fclose($f);

  }

回答1:


Assuming that your XML is actually valid (has a single root element) then a simplified view of the structure is this:

<document>
    <Cars>
       <Car>
          <Brand>Car1</Brand>
       </Car>
    </Cars>
    <Cars>
       <Car>
          <Brand>Car2</Brand>
       </Car>
    </Cars>
</document>

Note that there are multiple Cars nodes at the same level, but only one Car in each one.

When you load the XML, your initial PHP variable will represent the <document> element.

So you could access the first two brands by hand like this (the (string) gets the text content from the XML element):

  • (string)$xml->Cars[0]->Car->Brand
  • (string)$xml->Cars[1]->Car->Brand

To get all the brands, you need to loop over $xml->Cars:

foreach ( $xml->Cars as $CarsNode ) {
   $CarNode = $CarsNode->Car;
   $brand = (string)$CarNode->Brand;
}

From there, you can use your existing code to write a row to your CSV file.




回答2:


For each child node/tag you must use __toString() method.

Like that:

foreach ($xml->Car as $Car) {
    $row = [];
    foreach ($cname as $node) {
        // Here we address to the Car's child node with name from your array above
        $row[$node] = $Car->{$node}->__toString();
    }

    fputcsv($f, $row, ',' ,'"');
} 

fclose($f);


来源:https://stackoverflow.com/questions/57702289/xml-to-csv-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!