用于将.CSV文件转换为.XML的PHP​​脚本

前端之家收集整理的这篇文章主要介绍了用于将.CSV文件转换为.XML的PHP​​脚本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
只是想知道是否有人可以指向一些提示/脚本的方向,这将有助于我使用PHP从原始CSV文件创建XML.

干杯

这很容易做到,只需看fgetcsv读取csv文件然后再看DomDocument就可以编写一个xml文件.此版本使用文件中的标头作为xml文档的键.
  1. <?PHP
  2. error_reporting(E_ALL | E_STRICT);
  3. ini_set('display_errors',true);
  4. ini_set('auto_detect_line_endings',true);
  5.  
  6. $inputFilename = 'input.csv';
  7. $outputFilename = 'output.xml';
  8.  
  9. // Open csv to read
  10. $inputFile = fopen($inputFilename,'rt');
  11.  
  12. // Get the headers of the file
  13. $headers = fgetcsv($inputFile);
  14.  
  15. // Create a new dom document with pretty formatting
  16. $doc = new DomDocument();
  17. $doc->formatOutput = true;
  18.  
  19. // Add a root node to the document
  20. $root = $doc->createElement('rows');
  21. $root = $doc->appendChild($root);
  22.  
  23. // Loop through each row creating a <row> node with the correct data
  24. while (($row = fgetcsv($inputFile)) !== FALSE)
  25. {
  26. $container = $doc->createElement('row');
  27. foreach($headers as $i => $header)
  28. {
  29. $child = $doc->createElement($header);
  30. $child = $container->appendChild($child);
  31. $value = $doc->createTextNode($row[$i]);
  32. $value = $child->appendChild($value);
  33. }
  34.  
  35. $root->appendChild($container);
  36. }
  37.  
  38. $strxml = $doc->saveXML();
  39. $handle = fopen($outputFilename,"w");
  40. fwrite($handle,$strxml);
  41. fclose($handle);

猜你在找的XML相关文章