简体   繁体   中英

Convert CSV to XML using PHP

I have multiple CSV files in a folder with different data. I want to read in 1 CSV file at a time, convert the data to XML and then output the file as .xml before reading in the next CSV file.

Currently, the CSV files that I have all have a header row in it. The code I ave right now runs fine for all the CSV files that have a header row in it.

However, when it reads in a file that does not have a header row in it, it throws an error. I want it to be able to detect if there is no headings in the header row and then make it input strings which have been preset in variables in the code. Is this possible?

Current Code

function converttoxml( $input_filename ) {

echo $input_filename;

//set the delimiter
$delimiter = "," ;

//set count to 0
$row_count++ ;

//strip the input filename of the extension
$stripped = pathinfo($input_filename, PATHINFO_FILENAME);

//set output filename
$outputFilename  = UPLOAD_DIR."/".$stripped.".xml";

//open inputfilename
$inputFile  = fopen( $input_filename, 'rt' );

//get input file pointers for csv parsing
$headers = fgetcsv( $inputFile );

//create new DOM document
$doc  = new DomDocument();

//set the output to clean
$doc->formatOutput = true;

//create element
$root = $doc->createElement( 'Shipping_Details' );

$root = $doc->appendChild( $root );

//while there are rows in the csv file
while ( ( $row = fgetcsv( $inputFile ) ) !== FALSE ) {

    //create container row
    $container = $doc->createElement('Job_Header_Details');

        //for loop
        foreach ( $headers as $i => $header ) {

            //explode with the delimiter the header
            $arr = explode( $delimiter, $header );

            //print_r($arr);

                //for loop
                foreach ( $arr as $key => $ar ) {

                    //only accept regualar expressions matching this
                    $child = $doc->createElement(preg_replace( "/[^A-Za-z0-9]/","",$ar ) );

                    //add the previous child to $child
                    $child = $container->appendChild( $child );

                    //explode row with delimiter
                    $whole = explode( $delimiter, $row[$i] );

                    //left and right trim anything with speechmarks
                    $value = $doc->createTextNode( ltrim( rtrim( $whole[$key], '"') ,'"') );

                    //append previous value to $value
                    $value = $child->appendChild( $value );

                }//for
        }//for

   //append to root - container
   $root->appendChild($container);

}//while



echo "Saving the XML file\n" ;

$result = $doc->saveXML();

echo "Writing to the XML file\n" ;

$handle = fopen( $outputFilename, "w" );

fwrite( $handle, $result );

fclose( $handle );

return $outputFilename;

Examples of CSV files that will/willnot process

CSV File example that will work with above code

CSV File example that will NOT work with the above code

With the example that will not work, I believe it is because the header row is missing. In this case, I want to somehow define what each column heading should be and input it in.

for example

$column_1 = "<heading1>";
$column_2 = "<heading2>";
$column_3 = "<heading3>";
$column_4 = "<heading4>";
$column_5 = "<heading5>";
$column_6 = "<heading6>";

etc..

So when the script runs and it detects headings in the CSV file, it will use them. But when it detects that they are not there, the it will use the above $column examples to input the in.

The error I get when a CSV file does not have a header description

缺少标题错误

Any ideas?

Just to try this out, added ...

    //get input file pointers for csv parsing
    $headers = fgetcsv( $inputFile );

    $row = 1;
    foreach ( $headers as &$header )   {
        if (preg_match('/\A(?!XML)[a-z][\w0-9-]*/i', $header) === 0 ) {
           $header = 'heading'.$row;
        }
        $row++;
    }
    unset($header);

Which when passed in a header of a,1223 produces headers of a,heading2 . Whereas a,b gives a,b .

Update: Although if any element fails, you'll want to process this row as data by the look of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM