PHP Script to convert .CSV files to .XML

后端 未结 4 1923
抹茶落季
抹茶落季 2021-01-02 08:30

Just wondering if anyone can point me in the direction of some tips / a script that will help me create an XML from an original CSV File, using PHP.

Cheers

4条回答
  •  一整个雨季
    2021-01-02 09:01

    This is quite easy to do, just look at fgetcsv to read csv files and then DomDocument to write an xml file. This version uses the headers from the file as the keys of the xml document.

    formatOutput   = true;
    
    // Add a root node to the document
    $root = $doc->createElement('rows');
    $root = $doc->appendChild($root);
    
    // Loop through each row creating a  node with the correct data
    while (($row = fgetcsv($inputFile)) !== FALSE)
    {
        $container = $doc->createElement('row');
        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);
    

提交回复
热议问题