【发布时间】:2017-12-14 09:44:16
【问题描述】:
我在一个文件夹中有多个包含不同数据的 CSV 文件。我想一次读取 1 个 CSV 文件,将数据转换为 XML,然后将文件输出为 .xml,然后再读取下一个 CSV 文件。
目前,我拥有的所有 CSV 文件中都有一个标题行。我现在的代码对于所有包含标题行的 CSV 文件都运行良好。
但是,当它读取一个没有标题行的文件时,它会引发错误。我希望它能够检测标题行中是否没有标题,然后使其输入代码中变量中预设的字符串。这可能吗?
当前代码
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;
将/不会处理的 CSV 文件示例
CSV File example that will work with above code
CSV File example that will NOT work with the above code
对于不起作用的示例,我相信这是因为缺少标题行。在这种情况下,我想以某种方式定义每个列标题应该是什么并将其输入。
例如
$column_1 = "<heading1>";
$column_2 = "<heading2>";
$column_3 = "<heading3>";
$column_4 = "<heading4>";
$column_5 = "<heading5>";
$column_6 = "<heading6>";
等等。
因此,当脚本运行并检测到 CSV 文件中的标题时,它将使用它们。但是当它检测到它们不存在时,它会使用上面的 $column 示例来输入。
CSV 文件没有标头描述时出现的错误
有什么想法吗?
【问题讨论】:
-
当您阅读标题时,您必须检查每个名称是否是有效的 xml 元素名称,stackoverflow.com/questions/2519845/… 提供了一个正则表达式来检查它们,所以用这个解析每个并替换那些无效。
-
好问题。您可以编辑您的帖子并将 csv 文件添加为屏幕截图而不是文本吗?如何?只需在任何文本编辑器(不是 Excel 或其他电子表格应用程序)中打开 csv,然后将顶部的几行复制并粘贴到帖子正文中,使用工具栏上的 SO 的
{}按钮对其进行格式化。
标签: php xml csv data-conversion