问题描述
我正在尝试像这样将变量的制表符分隔内容写入XML:
I'm trying to write the tab-delimited content of a variable to XML like this:
$tsvData = str_getcsv($input, "\t");
foreach($tsvData as $line => $row) {
if($line > 0) {
$xmlWriter->writeElement('NAME', $row[0]);
$xmlWriter->writeElement('CAKE', $row[1]);
$xmlWriter->writeElement('BODYPART', $row[2]);
}
}
但是,每个XML标签只写一个字符,而不是每个标签之间写所有字符.当我使用SplFileObject时,从文件中获取相同的tsv数据,它可以工作.我的str_getcsv函数怎么了?
But it's only writing one character per XML tag instead of everything between each tab. When I use SplFileObject, geting the same tsv data but from a file, it works. What am I doing wrong with the str_getcsv function?
谢谢
推荐答案
str_getcsv()
函数返回一维数组,但是您将其视为返回二维数组.
The str_getcsv()
function returns a 1-dimensional array, but you're treating it like it's returning a 2-dimensional array.
为澄清起见,str_getcsv()
没有线"的概念.而不是这样做:
To clarify, str_getcsv()
has no concept of "lines". Instead of doing this:
$tsvData = str_getcsv($input, "\t");
以为您将获得一个由线组成的数组,每行包含一个列数组,您必须执行以下操作:
Thinking that you'll get an array of lines, each one containing an array of columns, you have to do something like this:
$lines = explode("\n", $input);
$tsvData = array();
foreach ($lines as $line) {
$tsvData[] = str_getcsv($line, "\t");
}
// now $tsvData is a 2-dimensional array of lines/columns like you were wanting
这篇关于制表符分隔的字符串,使用PHP转换为XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!