简体   繁体   English

如何使用PHP脚本将CSV文件转换为XML?

[英]How do I convert a CSV file to XML using PHP script?

I am trying to convert my CSV file to XML. 我正在尝试将CS​​V文件转换为XML。 I am using this script below which I got from a post. 我正在使用从帖子中获得的以下脚本。 But it's not working on my side. 但这对我不起作用。 Any idea why I am getting this error? 知道为什么我会收到此错误吗?

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

The error I am getting is here: 我收到的错误在这里:

 Uncaught exception 'DOMException' with message 'Invalid Character Error' 

Here is my csv file: 这是我的csv文件:

  name, email, test
  john,john@foobar.com,blah
  mary,mary@blah.com,something
  jane,jan@something.com,blarg
  bob,bob@test.com,asdfsfd

Your header row has spaces around the field names, spaces don't sit well with the names of XML elements. 标题行的字段名称周围有空格,空格与XML元素的名称不太匹配。 Simply trim() the field names... 只需trim()字段名称...

$child = $doc->createElement(trim($header));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM