Question

I need some help on an issue: I'm converting an XML to CSV using a PHP script, but i have a problem with this, they're a properties in properties.

This is the XML file structure:

<Products>
 <Product>
   <Name>
     SomeProductName
   </Name>
   <Colour>
     Black
   </Colour>
  <Features>
   <Feature_0>
     this is feature 0
   </Feature_0>
   <Feature_1>
     this is feature 1
   </Feature_1>
   <Feature_2>
     this is feature 1
   </Feature_2>
  </Features>
 <Product>
</Product>

and this is my script :

{$filexml='product.xml';
if (file_exists($filexml)) {
  $xml = simplexml_load_file($filexml);
  $f = fopen('product.csv', 'w');
foreach($xml->Products->Product as $product) {    
  $values = array(
   "Name" => $product->Name, 
   "Colour" => $product->Colour, 
   "Features" => $product->Features);
   fputcsv($f, $values,',','"');
  }
fclose($f);
}

with this script i only get Feature_0, and I need to get all those features in my csv file. Any help will be greatly appreciated.

Thanks in advance!

Was it helpful?

Solution

CSV isn't well suited for that sort of nested data.

Either you would have to create two csv files: prodcuts.csv and features.csv where entries from features.csv pointing to entries in products.csv, like in a relational database or you would have to flatten the feature list into a single string, so that the CSV would look like this:

"product_name", "product_color", "features"
"SomeProductName", "Black", "this is feature 0|this is feature 1|this is feature 2"
"AnotherProductName", "White", "this is feature foo|this is feature bar"

However the flatten function must make sure that the delimiter isn't part of the data itself.

I would encourage you to keep it xml, as it is best suited for nested data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top