2

我要导出到 XML 的 CSV 文件的字符集是 ASCII,所以它应该可以工作。

我认为该功能可能无法正确实现?不会抛出任何错误,但原始错误保持不变。

这是完整的错误代码:

致命错误:在 /home/paul/public_html/csv2xml.php:30 中未捕获的异常“DOMException”和消息“无效字符错误”堆栈跟踪:#0 /home/paul/public_html/csv2xml.php(30):DOMDocument-> createElement('Listdate (YYYY-...') #1 {main} 在第 30 行的 /home/paul/public_html/csv2xml.php 中抛出

<?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(htmlentities($header));
  $child = $container->appendChild($child);
     $value = $doc->createTextNode($row[$i]);
     $value = $child->appendChild($value);
 }

 $root->appendChild($container);
}

echo $doc->saveXML();
?>
4

2 回答 2

0

视运行 PHP 5.4+ 为条件,尝试 htmlentities 中的 ENT_XML1 标志:

$child = $doc->createElement(htmlentities($header, ENT_XML1));

如果您坚持使用旧版本的 PHP,我建议您在php.net 的 htmlentities 注释中找到任何类型的 XML 实体编码函数

于 2012-05-17T18:42:52.833 回答
0

由无效的元素名称引起DOMDocument->createElement()- 请参阅此答案

于 2017-12-01T14:24:00.637 回答