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 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制