【问题标题】:How do I convert a CSV file to XML using PHP script?如何使用 PHP 脚本将 CSV 文件转换为 XML?
【发布时间】:2017-10-28 07:40:20
【问题描述】:

我正在尝试将我的 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

【问题讨论】:

标签: php xml csv


【解决方案1】:

您的标题行在字段名称周围有空格,空格不适合 XML 元素的名称。只需 trim() 字段名称...

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

【讨论】:

    猜你喜欢
    • 2011-06-18
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2012-12-31
    • 1970-01-01
    • 2016-09-02
    • 2017-06-24
    相关资源
    最近更新 更多