gpt4 book ai didi

php - 将制表符分隔的文本文件转换为 XML

转载 作者:行者123 更新时间:2023-12-05 00:08:20 25 4
gpt4 key购买 nike

我想知道是否有一种公认的方法可以将制表符分隔的文本文件转换为 XML,以便可以将其导入 Adob​​e Flex。我更愿意使用 PHP 来实现这一点。

谢谢

编辑:

我要转换的制表符分隔文本文件的格式为

Refnumber  Location    Name     Age    
123 North America Steve 32

我希望转换为

<data>
<refnumber> 123 </refnumber>
<location> North America </location>
<name> Steve </name>
<age> 32 </age>
</data>

最佳答案

可以逐行遍历文件,用XMLWriter写入内容

XmlWriter 示例 ( demo )

$xmlWriter = new XMLWriter();
$xmlWriter->openUri('/path/to/destination.xml');
$xmlWriter->setIndent(true);
$xmlWriter->startDocument('1.0', 'UTF-8');
$xmlWriter->startElement('root');

$tsvFile = new SplFileObject('filename.tsv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
foreach ($tsvFile as $line => $row) {
if($line > 0) {
$xmlWriter->startElement('data');
$xmlWriter->writeElement('refnumber', $row[0]);
$xmlWriter->writeElement('location', $row[1]);
$xmlWriter->writeElement('name', $row[2]);
$xmlWriter->writeElement('age', $row[3]);
$xmlWriter->endElement();
}
}
$xmlWriter->endElement();
$xmlWriter->endDocument();

使用 XmlWriter 有一个额外的好处,当您试图为 XML 元素编写非法内容时,它会告诉您。如果您知道 tsv 文件中只有有效数据,您也可以只使用模板并将其写入另一个文件。

模板示例 ( demo )

$tsvFile = new SplFileObject('filename.tsv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");

$template = <<< TPL
<data>
<refnumber>%d</refnumber>
<location>%s</location>
<name>%s</name>
<age>%d</age>
</data>
TPL;

$destFile = new SplFileObject('destination.xml', 'w+');
$destFile->fwrite('<?xml version="1.0" encoding="UTF-8"?>');
$destFile->fwrite("\n<root>\n");
foreach ($tsvFile as $line => $row) {
if($line > 0) {
$destFile->fwrite(vsprintf($template, $row));
}
}
$destFile->fwrite('</root>');

链接

关于php - 将制表符分隔的文本文件转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6141572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com