Question

So I have an XML file that looks similar to this:

<container>
<example1>some text</example1>
<example2>some text</example2>
<example3>some text</example3>
<example4>some text</example4>
</container>
<container>
<example1>some text</example1>
<example2>some text</example2>
<example4>some text</example4>
</container>

Basically, if example3 doesn't contain any information, the XML author decided to leave it out completely. The trouble is, when I am using my script to convert to CSV, this particular XML file doesn't convert to CSV properly due to the text in the second example4 being displayed under the header of example3 in the CSV file.

This is the PHP script I have to normally works with other XML files.

$file='input.xml';
if (file_exists($file)) {
    $xml = simplexml_load_file($file);
    $f = fopen('output.csv', 'w');

    // array to hold the field names
    $headers = array(); 
    // loop through the first set of fields to get names
    foreach ($xml->container->children() as $field) { 
        // put the field name into array
        $headers[] = $field->getName(); 
    }
    // print headers to CSV
    fputcsv($f, $headers, ',', '"');

    foreach ($xml->container as $information) {
        fputcsv($f, get_object_vars($information), ',', '"');
    }
    fclose($f);
}

I can't figure out how to predefine the headers that I need and insert the correct information in the correct columns in the CSV.

Any pointers much appreciated.

thanks

mike

Was it helpful?

Solution

If your first entry always present all fields, then its enougth to iterate over the header fields for each line and look if the current line has all entrys.

foreach ($xml->container as $information) {
    $vars = get_object_vars($information);
    $line = array();
    foreach($headers as $field) {
        $line[] = isset($vars[$field]) ? $vars[$field] : '';
    }
    fputcsv($f, $line, ',', '"');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top