PHP Script to convert .CSV files to .XML

后端 未结 4 1924
抹茶落季
抹茶落季 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 08:49

    Sorry to bring up an old thread but I tried this script and I'm getting a DOM Exception error

    The headers of our CSV Files are display_name office_number mobile_number and the error I'm receiving is DOMDocument->createElement('\xEF\xBB\xBFdisplay_name') #1 {main}

    0 讨论(0)
  • 2021-01-02 08:52

    The code given above creates an XML document, but does not store it on any physical device. So replace echo $doc->saveXML(); with

    $strxml = $doc->saveXML();
    $handle = fopen($outputFilename, "w");
    fwrite($handle, $strxml);
    fclose($handle);
    
    0 讨论(0)
  • 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.

    <?php
    error_reporting(E_ALL | E_STRICT);
    ini_set('display_errors', true);
    ini_set('auto_detect_line_endings', true);
    
    $inputFilename    = 'input.csv';
    $outputFilename   = 'output.xml';
    
    // Open csv to read
    $inputFile  = fopen($inputFilename, 'rt');
    
    // Get the headers of the file
    $headers = fgetcsv($inputFile);
    
    // Create a new dom document with pretty formatting
    $doc  = new DomDocument();
    $doc->formatOutput   = true;
    
    // Add a root node to the document
    $root = $doc->createElement('rows');
    $root = $doc->appendChild($root);
    
    // Loop through each row creating a <row> 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);
    
    0 讨论(0)
  • 2021-01-02 09:08

    There are a number of sites out there that will do it for you.

    If this is going to be a regular process rather than a one-time thing it may be ideal to just parse the CSV and output the XML yourself:

    $csv = file("path/to/csv.csv");
    
    foreach($csv as $line)
    {
        $data = explode(",", $line);
        echo "<xmltag>".$data[0]."</xmltag>";
        //etc...
    }
    

    Look up PHP's file and string functions.

    0 讨论(0)
提交回复
热议问题