tab-delimited string to XML with PHP

六月ゝ 毕业季﹏ 提交于 2019-12-12 04:27:21

问题


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]);
    }
}

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?

Thanks


回答1:


The str_getcsv() function returns a 1-dimensional array, but you're treating it like it's returning a 2-dimensional array.

Edit:

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


来源:https://stackoverflow.com/questions/7423800/tab-delimited-string-to-xml-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!