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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4852796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:05:09  来源:igfitidea点击:

PHP Script to convert .CSV files to .XML

phpxmlcsv

提问by StuBlackett

Just wondering if anyone can point me in the direction of some tips / a script that will help me create an XML from an original CSV File, using PHP.

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

Cheers

干杯

回答by Michael Parkin

This is quite easy to do, just look at fgetcsv to read csv files and then DomDocument to write an xml file. This version uses the headers from the file as the keys of the xml document.

这很容易做到,只需查看 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);

回答by Nirmal Sharma

The code given above creates an XML document, but does not store it on any physical device. So replace echo $doc->saveXML();with

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

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

回答by Ben L.

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

有许多网站可以为您做这件事

If this is going to be a regular process rather than a one-time thing it may be ideal to just parse the CSV and output the XML yourself:

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

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

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

Look up PHP's fileand stringfunctions.

查找 PHPfilestring函数。