【发布时间】:2015-07-04 02:07:58
【问题描述】:
我遇到了以下问题:
我有一个 csv 文件,我可以通过 php 脚本将其转换为 XML。
这样,每个字段都在 xml 中的同一行下,我希望 product_sku 字段在不同的行下,例如将其命名为 SKU_row。
CSV 看起来像这样:
XML 如下所示:
我运行的将 CSV 转换为 XML 的 PHP 文件代码:
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
function PrepareXMLName($PrepareString)
{
$PrepareString = str_replace(" ","",$PrepareString);
$PrepareString = preg_replace('#\W#', '', $PrepareString);
$PrepareString = str_replace("ZSPAZESZ","",$PrepareString);
$PrepareString = strtolower($PrepareString);
return $PrepareString;
}
$inputFilename = 'faszom.csv';
$outputFilename = 'faszom.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)
{
$header = str_replace(chr(32),"_",trim($header));
$header = strtolower($header);
if($header==''){ $header = 'empty';}
$header = PrepareXMLName($header);
if(is_numeric($header)) { $header = "number-". $header; }
//echo "HERE: " . $header . "<br />";
$child = $doc->createElement($header);
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
header("Content-type: text/xml");
$strxml = $doc->saveXML();
$handle = fopen($outputFilename, "w");
fwrite($handle, $strxml);
fclose($handle);
echo $doc->saveXML();
我该如何在这个 PHP 文件中,让它将 product_sku 字段放在不同的行下,使其与客户数据所在的行分开?
【问题讨论】: