The character set of the CSV file I'm exporting to XML is ASCII so it should be working.

I think the function may not be implemented correctly? No errors are thrown but the original error remains unchanged.

Here's the full error followed by the code:

Fatal error: Uncaught exception 'DOMException' with message 'Invalid Character Error' in /home/paul/public_html/csv2xml.php:30 Stack trace: #0 /home/paul/public_html/csv2xml.php(30): DOMDocument->createElement('Listdate (YYYY-...') #1 {main} thrown in /home/paul/public_html/csv2xml.php on line 30

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

There are 2 answers

1
matb33 On

Contingent on running PHP 5.4+, try the ENT_XML1 flag in htmlentities:

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

If you are stuck with an older version of PHP, I suggest grabbing any of the flavors of XML entity encoding functions found in the php.net comments for htmlentities

0
Mark Townsend On

Caused by an invalid element name in DOMDocument->createElement() - See this answer