Search code examples
phpxmlcsvfputcsv

XML to CSV in PHP


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

  }

Solution

  • 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.