CSV到XML,删除一些行? (PHP)

时间:2017-02-21 15:29:21

标签: php xml csv dom simplexml

因为我将一些XML文件从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);
}

我现在的问题是,我有一个包含标题的数组。标题与我的标题数组匹配的所有CSV行都不应转换为XML。但是我该怎么做呢? - 我还需要通过mb_...(多字节)函数来检查它!

另一个选项是在转换之前删除我的标题数组与行中的标题匹配的行。也许这更聪明? - 或者最好在导入时检查一下?

编辑(添加CSV示例): File 1 File 2

问候,谢谢!

0 个答案:

没有答案
相关问题