You are here:  » adding row information from XML to CSV


adding row information from XML to CSV

Submitted by visserlabs on Sun, 2009-12-27 04:02 in

Hi,

I have an XML file which I'd very much to bring across the attribute names (e.g. stockCode, stockName, unitWeight, etc.) as row headers in my outputted CSV file. How can I do this?

Submitted by support on Sun, 2009-12-27 08:40

Hello,

Have you already made progress with your XML to CSV conversion but without the attributes? You'll find a very basic XML to CSV script here...

http://www.magicparser.com/node/464

...and that should include all values in each $record of your XML source - which will include both regular element values and attributes.

If you only wanted to output specific fields; then instead of:

    fwrite($csv,implode(",",$record)."\n");

...you could use something like:

    fwrite($csv,$record["NAME"].",");
    fwrite($csv,$record["PRODUCT-STOCKCODE"].",");
    fwrite($csv,$record["PRODUCT-UNITWEIGHT"]."\n");

The $record key values with a hyphen are attributes - so in the above example, STOCKWEIGHT would be an attribute of the <product> element.

If you're not sure; perhaps you could email me an example or link to the XML that you're working with; and a description of which fields you would like exporting to CSV and i'll help you out. The output can either be to a file as in the example from the other thread (don't forget to make sure that PHP can write to the output file) or simply output the CSV to the browser / force for download.

Perhaps the easiest way to make sure that PHP can write your CSV file is instead of using...

  $csv = "file.csv";

...create a sub-directory called "output", and then make that directory writable by all users. The easiest way to do this is normally with your FTP program. Right-click on the new folder and look for Permissions... or maybe Properties... and then Permissions. Then give WRITE access to all users - Owner / Group / World. Finally, change the above line to:

  $csv = "output/file.csv";

I'm on the road today but will be back online later this afternoon if you require any more assistance...

Regards,
David
--
MagicParser.com