Mic*_*kin 16
这很容易做到,只需看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);
Run Code Online (Sandbox Code Playgroud)
小智 6
上面给出的代码创建了一个XML文档,但不会将其存储在任何物理设备上.因此,更换echo $doc->saveXML();用
$strxml = $doc->saveXML();
$handle = fopen($outputFilename, "w");
fwrite($handle, $strxml);
fclose($handle);
Run Code Online (Sandbox Code Playgroud)
如果这是一个常规的过程而不是一次性的事情,那么解析CSV并自己输出XML可能是理想的:
$csv = file("path/to/csv.csv");
foreach($csv as $line)
{
$data = explode(",", $line);
echo "<xmltag>".$data[0]."</xmltag>";
//etc...
}
Run Code Online (Sandbox Code Playgroud)
查找PHP file和string函数.
| 归档时间: |
|
| 查看次数: |
24718 次 |
| 最近记录: |