获取无效字符DOMException错误.I';我实现了htmlentities来更改特殊字符,但运气不好


Getting an invalid character DOMException error. I've implemented htmlentities to change special characters but no luck

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

我认为这个功能可能没有正确实现?没有抛出任何错误,但原始错误保持不变。

以下是完整的错误,后面跟着代码:

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

<?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();
?>

取决于运行PHP 5.4+,请尝试htmlenties:中的ENT_XML1标志

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

如果您使用的是旧版本的PHP,我建议您使用htmlentities 的PHP.net注释中的任何一种XML实体编码函数。

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