【发布时间】:2017-02-21 17:47:26
【问题描述】:
我有一个 CSV 文件,我想检查该行是否包含特殊标题。仅当我的行包含特殊标题时,它才应转换为 XML,添加其他内容等等。
我现在的问题是,如何遍历整个 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);
}
【问题讨论】: