douli2876 2017-07-10 15:14
浏览 114

使用PHP将CSV转换为XML

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
" ;

$result = $doc->saveXML();

echo "Writing to the XML file
" ;

$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

Missing header error

Any ideas?

  • 写回答

1条回答 默认 最新

  • douchun1961 2017-07-10 15:41
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示