[英]Error convert .CSV to .XML using PHP Script
我正在嘗試將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行
我試圖“修剪”頁眉,但無法正常工作...
除非&
轉換為&
否則&
字符將破壞您的XML &
$fixed = htmlspecialchars('&'); // output &
響應:
顯然,“ fgetcsv”具有預定義的分隔符類型,在這種情況下為“,”。 具有CSV,以“;”分隔 它沒有檢測到它。
我在使用分隔符的兩行中定義了分隔符,如下所示:
$headers = fgetcsv($inputFile, '0', ';');
while (($row = fgetcsv($inputFile, '0', ';')) !== FALSE)
這樣,一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.