简体   繁体   English

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

[英]PHP Script to convert .CSV files to .XML

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干杯

This is quite easy to do, just look at fgetcsv to read csv files and then DomDocument to write an xml file.这很容易做到,只需查看 fgetcsv 读取 csv 文件,然后查看 DomDocument 写入 xml 文件。 This version uses the headers from the file as the keys of the xml document.此版本使用文件中的标题作为 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);

The code given above creates an XML document, but does not store it on any physical device.上面给出的代码创建了一个 XML 文档,但没有将它存储在任何物理设备上。 So replace echo $doc->saveXML();所以替换echo $doc->saveXML(); with

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

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 file and string functions.查找 PHP 的filestring函数。

Sorry to bring up an old thread but I tried this script and I'm getting a DOM Exception error很抱歉提出一个旧线程,但我尝试了这个脚本,但出现了 DOM 异常错误

The headers of our CSV Files are display_name office_number mobile_number and the error I'm receiving is DOMDocument->createElement('\\xEF\\xBB\\xBFdisplay_name') #1 {main}我们的 CSV 文件的标题是 display_name office_number mobile_number 我收到的错误是 DOMDocument->createElement('\\xEF\\xBB\\xBFdisplay_name') #1 {main}

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

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