Skip to content
Advertisement

Convert XML to CSV with PHP, with different fields in some itens

I want to convert a XML to a CSV. That’s OK, but in some itens, I have extra fields or less fields than other itens.

A example of my feed is:

EDIT: The top of the XML is:

JavaScript

Item with less fields:

JavaScript

Item with most common fields:

JavaScript

Item with more fields:

JavaScript

I’m using a script to do the conversion, it works, but it gets wrong when the item have more or less fields than the most common type of item.

JavaScript

With this script, I get always a sequential order of the fields of each item. Because of that, the data doesn’t match the header of the column many times, and some items with more fields don’t have header because of it.

Sorry, I’m not a PHP developer, and it is hard to me to solve this. I tried to search here, but didn’t find a problem like mine.

Thanks

Advertisement

Answer

Simply iterate off the columns array you use for the CSV headers where you pass column name into the XPath expression not all item’s children with /*. To select the first item of returned XPath array the [0] index is used and to remove whitespace, trim() is used.

Also, you will need to register the namespace prefix g to access those elements (hence why namespaces are important to always include in posted XML snippets):

JavaScript

Do note column headers will have the g: prefix for those applicable columns. Maybe use two nearly same arrays one for headers and other for XPath calls.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement