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

标签 php xml csv

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

干杯

最佳答案

这很容易做到,只需看fgetcsv 读取csv 文件,然后看DomDocument 写入xml 文件。此版本使用文件中的 header 作为 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);

关于将 .CSV 文件转换为 .XML 的 PHP 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4852796/

相关文章:

python - 计算 CSV 中的属性值?

php - SQLSTATE[HY000] [2003] 无法在 '127.0.0.1' (61) 错误上连接到 MySQL 服务器 Laravel 4.1

javascript - 如何仅通过 Javascript 访问我的 GrapheneDB neo4j 数据库

json - 选择键:value with jq and output as array

android - 使用 XML(Android API 级别 23)在警报对话框中设置消息文本外观

android - 如何更改 TextInputLayout 的提示大小

node.js - Node-RED docker 读取目录内容的问题

php - POST 表单显示错误回显

php - Laravel 5.4 中表之间的多重关系

Android自定义键盘布局在侧面留下白色边距