PHP School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a PHP Expert!

Join 307,026 PHP Programmers for FREE! Get instant access to thousands of PHP experts, tutorials, code snippets, and more! There are 2,201 people online right now. Registration is fast and FREE... Join Now!




CSV to XML conversion script

 

CSV to XML conversion script, There is a bug I can't find in my script...

THX1138

6 Nov, 2009 - 05:28 AM
Post #1

New D.I.C Head
*

Joined: 14 Dec, 2007
Posts: 16


My Contributions
Hi everybody,

For the past week I've been coding a little php shell script to convert CSV files (exported from Excel sheets) to a specific XML template. Before I explain what the actual problem is, here is the code I wrote:

CODE

#!/usr/bin/php -q
<?php

// Configuration
$length    =    1024; # max length of a line in a csv file
$delimiter =     ';';
$csv       = array(); # the content of the csv will be converted to arrays line by line and each array will be pushed in the $csv array

// Working directory
$dirs = (count($argv) == 1) ? '.' : $argv;

if (is_array($dirs))
{
    foreach ($dirs as $dir) {
        if ($dir === $argv[0])
            continue;
        if (is_dir($dir))
        {
            $dirname = $dir;
            $dir = realpath('.').'/'.$dir;
            chdir($dir);
            if ($handle = opendir($dir))
            {
                while(($file = readdir($handle)) !== FALSE)
                {
                    // read only csv files with a name similar to: 1234567890.csv (13 numbers strictly); normaly there should be only one per directory.
                    if (preg_match('/^\d{13}\.csv$/', $file, $match) != 0 )
                    {
                        if(($h = fopen($match[0], 'r')) !== FALSE)
                        {
                            while (!feof($h))
                            {
                                array_push($csv, fgetcsv($h, $length, $delimiter));
                            }
                        }
                        fclose($h);
                        
                        // Reformat the csv array.
                        $number_of_tracks = count($csv);
                        $number_of_tracks--;
                        $temp_csv = array();
                        for ($k=1; $k < $number_of_tracks; $k++)
                        {
                            $max = count($csv[$k]);
                            $temp_csv_track = array();
                            for ($i=0; $i < $max; $i++)
                            {
                                $temp_csv_track[$csv[0][$i]] = $csv[$k][$i];
                            }
                            array_push($temp_csv, $temp_csv_track);
                        }
                        $csv = $temp_csv;
                        
                        $disc_num = 1;
                        
                        // First we create the content of the XML file
                        
                        # Creation du contenu du fichier XML
                        $xml  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
                        $xml .= "<reference barcode=\"${dirname}\">\n";
                        $xml .= "\t<title><![CDATA[{$csv[0][4]}]]></title>\n";
                        if(in_array('album', $csv[0]) !== FALSE)
                        {
                            // TODO - Verify that the album field is not empty
                            // NOTE - Now I verify $csv[0][2] but the album element might be at a different position in the array.
                            $xml .= "\t<artist><![CDATA[{$csv[0][2]}]]></artist>";
                        }
                        $xml .= "\t<disk id=\"1\">\n";
                        foreach ($csv as $track)
                        {
                            if ($track == $csv[0])
                                continue;
                            // check the disc number
                            // NOTE - Sur les premiers discs rippes le numero du disc est dans le champ gallete
                            if ($track['galette'] > $disc_num)
                            {
                                $xml .= "\t</disc>\n";
                                $disc_num++;
                                $xml .= "\t<disc id=\"${disc_num}\">\n";
                            }
                            $duration = (empty($track['minutes'])) ? $track['sec'] : $track['minutes'] . $track['sec'];
                            $xml .= "\t\t<track id=\"{$track['track_num']}\" duration=\"${duration}\">\n";
                            $xml .= "\t\t\t<title><![CDATA[{$track['titre']}]]></title>\n";
                            // $xml .= (array_key_exists('artist', $track) === TRUE && !empty($track['artist'])) ? "<artist><![CDATA[{$track['track_artist']}]]></artist>\n" : "<artist></artist>\n";
                            $xml .= (array_key_exists('artist', $track) === TRUE && !empty($track['artist'])) ? "\t\t\t<artist><![CDATA[{$track['track_artist']}]]></artist>\n" : "";
                            $xml .= "\t\t</track>\n";
                        }
                        $xml .= "\t</disc>\n";
                        $xml .= "</reference>\n";
                        # FIN de Creation du contenu du fichier XML
                        
                        // Now we need to create the XML file and put the content in it
                        $xml_file_name = $dirname . '.xml';
                        if ($x = fopen($xml_file_name, 'w'))
                        {
                            fwrite($x, $xml);
                            fclose($x);
                        }
                        
                    }
                }
                closedir($handle);
            }
            chdir('..');
        }
    }
}


I called the script mcsvxml. I should be able to use that script using one of these three commands:
- mcsvxml foldername/
- mcsvxml .
- mcsvxml *

However only the first command works. If I use the second command, nothing happens. If I use the third command the XML files get created with the template in them but the values from the CSV are not inserted in the template (in other words I get an empty XML template in each folder where there is a CSV file) except for the first xml file created. This means that for some reason the $csv array is emptied (which is normal) but not repopulated, unless I'm wrong.

Can someone spot where there might be an error please?

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 08:18AM

Live PHP Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

PHP Tutorials

Reference Sheets

PHP Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month