猿问

使用 PHP 脚本将 .CSV 转换为 .XML 时出错

我正在尝试将我的 CSV 文件转换为 XML 以导入我的 PrestaShop。我正在使用这个脚本,下面是我从帖子中获得的。但它不起作用。


function createXML(){

    error_reporting(E_ALL | E_STRICT);

    ini_set('display_errors', true);

    ini_set('auto_detect_line_endings', true);


    $inputFilename    = 'import/products_import.csv';

    $outputFilename   = 'import/productos.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(trim($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);

    echo ('ejecutado');

}

我得到的错误是:


致命错误:未捕获的 DOMException:C:\xampp\htdocs\prestashop-devel\admin\productsImportWS.php 中的无效字符错误:52 堆栈跟踪:#0 C:\xampp\htdocs\prestashop-devel\admin\productsImportWS.php( 52): DOMDocument->createElement('Product ID;Acti...') #1 C:\xampp\htdocs\prestashop-devel\admin\productsImportWS.php(73): createXML() #2 {main} 抛出C:\xampp\htdocs\prestashop-devel\admin\productsImportWS.php 在第 52 行


我试图“修剪”标题,但它不起作用......


心有法竹
浏览 215回答 2
2回答

森栏

回复:显然“fgetcsv”有一个预定义类型的分隔符,在这种情况下是“,”。通过使用 CSV,以“;”分隔 它没有检测到它。我在使用它的两行中将分隔符定义如下:$headers = fgetcsv($inputFile, '0', ';');while (($row = fgetcsv($inputFile, '0', ';')) !== FALSE)通过这样做,一切正常。

慕田峪7331174

喜欢的字符&会破坏你的XML,除非转换为&amp;$fixed&nbsp;=&nbsp;htmlspecialchars('&');&nbsp;&nbsp;&nbsp;//&nbsp;output&nbsp;&amp;https://3v4l.org/K7slG
随时随地看视频慕课网APP
我要回答