PHP脚本将.CSV文件转换为.XML [英] PHP Script to convert .CSV files to .XML

查看:177
本文介绍了PHP脚本将.CSV文件转换为.XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道是否有人可以指向我的方向一些提示/一个脚本,将帮助我从原始的CSV文件中使用PHP创建一个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.

干杯

推荐答案

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

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.

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

这篇关于PHP脚本将.CSV文件转换为.XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆