Search code examples
phpxmlcsv

CSV2XML using PHP - need to add a line to output XML


I found the following code online and it works fine for me. I need to convert and CSV file to an XML file. The only thing I need to change is to make the code to output the same XML structure adding the line of the rss version as I mentioned below to my examples.

<?php
     // Map CSV file to array
      $rows = array_map('str_getcsv', file('data.csv'));
      $header = array_shift($rows);
      $data = array();
       foreach ($rows as $row)
      {
        $data[] = array_combine($header, $row);
      }
     // Process Data if need be
       foreach($data AS $key => $val)
     {
        // Processing here
      }
      //Creates XML string and XML document using the DOM 
      $xml = new DomDocument('1.0', 'UTF-8');

      //Add root node
      $root = $xml->createElement('channel');
      $xml->appendChild($root);

      // Add child nodes
      foreach($data AS $key => $val) 
  { 
$entry = $xml->createElement('item');
$root->appendChild($entry);

foreach($val AS $field_name => $field_value) 
{   
    $field_name = preg_replace("/[^A-Za-z0-9]/", '', $field_name); // preg_replace has the allowed characters
    $name = $entry->appendChild($xml->createElement($field_name)); 
    $name->appendChild($xml->createCDATASection($field_value)); 
  }
}
 // Set the formatOutput attribute of xml to true
 $xml->formatOutput = true; 
 // Output to screen
 // header('Content-Type: text/xml');
 // echo $xml->saveXML();
 // Save as file
    $xml->save('xml-import.xml'); // save as file
    ?>

The code mentioned above outputs the following XML structure:

<channel>
 <item>
 <title>
  <![CDATA[ pablo1 ]]>
 </title>
 <description>
  <![CDATA[ this is description 1 ]]>
 </description>
 <link>
  <![CDATA[ http://www.link1.com ]]>
 </link>
 </item>
</channel>

Someone knows how to update the code in order to output the following XML structure? Basically I need to add the rss version="2.0" line.

<rss version="2.0">
 <channel>
  <item>
   <title>
    <![CDATA[ pablo1 ]]>
   </title>
   <description>
    <![CDATA[ this is description 1 ]]>
   </description>
   <link>
    <![CDATA[ http://www.link1.com ]]>
   </link>
  </item>
 </channel>
</rss>

Thank you all for your help!


Solution

  • You can nest the element...

    $root = $xml->createElement('channel');
    $rss = $xml->createElement('rss');
    $rss->setAttribute("version","2.0");
    $rss->appendChild($root);
    $xml->appendChild($rss);