用于将.CSV文件转换为.XML的PHP​​脚本

时间:2011-01-31 15:46:08

标签: php xml csv

只是想知道是否有人可以指向一些提示/脚本的方向,这将有助于我使用PHP从原始CSV文件创建XML。

干杯

4 个答案:

答案 0 :(得分:15)

这很容易做到,只需看fgetcsv读取csv文件然后再看DomDocument来编写一个xml文件。此版本使用文件中的标头作为xml文档的键。

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

    $root->appendChild($container);
}

$strxml = $doc->saveXML();
$handle = fopen($outputFilename, "w");
fwrite($handle, $strxml);
fclose($handle);

答案 1 :(得分:6)

上面给出的代码创建了一个XML文档,但不会将其存储在任何物理设备上。所以用{/ p>替换echo $doc->saveXML();

$strxml = $doc->saveXML();
$handle = fopen($outputFilename, "w");
fwrite($handle, $strxml);
fclose($handle);

答案 2 :(得分:5)

There are a number of sites out there that will do it for you

如果这是一个常规的过程而不是一次性的事情,那么解析CSV并自己输出XML可能是理想的:

$csv = file("path/to/csv.csv");

foreach($csv as $line)
{
    $data = explode(",", $line);
    echo "<xmltag>".$data[0]."</xmltag>";
    //etc...
}

查找PHP的filestring函数。

答案 3 :(得分:1)

很抱歉打开一个旧线程,但是我尝试了此脚本,但出现了DOM异常错误

我们CSV文件的标题为display_name office_number mobile_number,我收到的错误是DOMDocument-> createElement('\ xEF \ xBB \ xBFdisplay_name')#1 {main}

相关问题