【问题标题】:Iterate through a CSV file and get every value for a specified header?遍历 CSV 文件并获取指定标头的每个值?
【发布时间】: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);
}

【问题讨论】:

    标签: php xml csv dom


    【解决方案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);
        }
      }
    

    【讨论】:

    • 但是为什么$row[1]
    • fgetcsv 从 CSV 行返回一个字段数组。由于您的Title 在第二列,它应该是@index 1。
    • 我明白了 :D - 但我不知道为什么我的 IDE 不接受我的代码......如果它被接受了???图片..drive.google.com/open?id=0BzLxINxZFzova2dDYm50YkplWTg
    • 您在if 声明中缺少结束)..!
    • 哈哈,我错过了结束)。更新了我的答案..!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2022-07-28
    • 2020-05-15
    相关资源
    最近更新 更多