迭代CSV文件并获取指定标题的每个值?

时间:2017-02-21 17:47:26

标签: php xml csv dom

我有一个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);
}

1 个答案:

答案 0 :(得分:1)

在将行添加到XML之前,只需检查标题。您可以通过添加以下行来完成:

 while (($row = fgetcsv($inputFile, 0, $delimiter)) !== false) {

    $specialTitles = Array('Title 1', 'Title 2', 'Title 3'); // titles you want to keep

    if(in_array($row[1], $specialTitles)){
        $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);
    }
  }
相关问题