【发布时间】:2017-10-28 07:40:20
【问题描述】:
我正在尝试将我的 CSV 文件转换为 XML。我正在使用这个脚本,下面是我从帖子中获得的。但这对我不起作用。知道为什么我会收到此错误吗?
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
$inputFilename = 'test.csv';
$outputFilename = 'test.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();
我得到的错误在这里:
Uncaught exception 'DOMException' with message 'Invalid Character Error'
这是我的 csv 文件:
name, email, test
john,john@foobar.com,blah
mary,mary@blah.com,something
jane,jan@something.com,blarg
bob,bob@test.com,asdfsfd
【问题讨论】:
-
@MikeyBunny 是的,我正在关注那个帖子。但这对我不起作用。
-
能否包含您的 CSV 文件,即使是前几行也会有所帮助。