用于将.CSV文件转换为.XML的PHP??脚本
发布时间:2020-12-16 07:58:53 所属栏目:百科 来源:网络整理
导读:只是想知道是否有人可以指向一些提示/脚本的方向,这将有助于我使用PHP从原始CSV文件创建XML. 干杯 这很容易做到,只需看fgetcsv读取csv文件然后再看DomDocument就可以编写一个xml文件.此版本使用文件中的标头作为xml文档的键. ?phperror_reporting(E_ALL | E_
只是想知道是否有人可以指向一些提示/脚本的方向,这将有助于我使用PHP从原始CSV文件创建XML.
干杯
这很容易做到,只需看fgetcsv读取csv文件然后再看DomDocument就可以编写一个xml文件.此版本使用文件中的标头作为xml文档的键.
<?php error_reporting(E_ALL | E_STRICT); ini_set('display_errors',true); ini_set('auto_detect_line_endings',true); $inputFilename = 'input.csv'; $outputFilename = 'output.xml'; // Open csv to read $inputFile = fopen($inputFilename,'rt'); // Get the headers of the file $headers = fgetcsv($inputFile); // Create a new dom document with pretty formatting $doc = new DomDocument(); $doc->formatOutput = true; // Add a root node to the document $root = $doc->createElement('rows'); $root = $doc->appendChild($root); // Loop through each row creating a <row> node with the correct data while (($row = fgetcsv($inputFile)) !== FALSE) { $container = $doc->createElement('row'); foreach($headers as $i => $header) { $child = $doc->createElement($header); $child = $container->appendChild($child); $value = $doc->createTextNode($row[$i]); $value = $child->appendChild($value); } $root->appendChild($container); } $strxml = $doc->saveXML(); $handle = fopen($outputFilename,"w"); fwrite($handle,$strxml); fclose($handle); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |