0
我有一个CSV文件,我想检查该行是否包含特殊标题。只有当我的行包含特殊标题时,它才应该转换为XML,添加其他内容等等。遍历CSV文件并获取指定头文件的每个值?
我现在的问题是,我怎样才能遍历整个CSV文件,并获得每个标题的价值在这个领域?
因为如果它匹配我的特殊标题,我只想将标题与我的标题匹配的指定行转换。也许也是一个想法,我可以做到这一点?
样品:CSV File
我必须补充,功能到我的实际功能。因为我的实际功能只是将整个CSV转换为XML。但我只想转换指定的行。
我的实际功能:
function csvToXML($inputFilename, $outputFilename, $delimiter = ',')
{
// Open csv to read
$inputFile = fopen($inputFilename, 'rt');
// Get the headers of the file
$headers = fgetcsv($inputFile, 0, $delimiter);
// Create a new dom document with pretty formatting
$doc = new DOMDocument('1.0', 'utf-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('products');
$root = $doc->appendChild($root);
// Loop through each row creating a <row> node with the correct data
while (($row = fgetcsv($inputFile, 0, $delimiter)) !== false) {
$container = $doc->createElement('product');
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);
}
问候和感谢!
但是为什么'$ row [1]'? – Jan
'fgetcsv'从CSV行中返回一个字段数组。由于你的'标题'在第二列,它应该是@索引1. – BizzyBob
我明白了:D - 但我不知道为什么我的IDE不接受我的代码... 没有,如果它被接受?图片.. https://drive.google.com/open?id=0BzLxINxZFzova2dDYm50YkplWTg – Jan