我正在尝试将我的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
答案 0 :(得分:0)
您的标题行在字段名称周围有空格,空格不能与XML元素的名称保持一致。只需修剪()字段名称......
$child = $doc->createElement(trim($header));