我在网上找到了以下代码,它对我来说很好。 我需要将CSV文件转换为XML文件。 我唯一需要改变的是让代码输出相同的XML结构,将我在下面提到的rss版本的行添加到我的示例中。
<?php
// Map CSV file to array
$rows = array_map('str_getcsv', file('data.csv'));
$header = array_shift($rows);
$data = array();
foreach ($rows as $row)
{
$data[] = array_combine($header, $row);
}
// Process Data if need be
foreach($data AS $key => $val)
{
// Processing here
}
//Creates XML string and XML document using the DOM
$xml = new DomDocument('1.0', 'UTF-8');
//Add root node
$root = $xml->createElement('channel');
$xml->appendChild($root);
// Add child nodes
foreach($data AS $key => $val)
{
$entry = $xml->createElement('item');
$root->appendChild($entry);
foreach($val AS $field_name => $field_value)
{
$field_name = preg_replace("/[^A-Za-z0-9]/", '', $field_name); // preg_replace has the allowed characters
$name = $entry->appendChild($xml->createElement($field_name));
$name->appendChild($xml->createCDATASection($field_value));
}
}
// Set the formatOutput attribute of xml to true
$xml->formatOutput = true;
// Output to screen
// header('Content-Type: text/xml');
// echo $xml->saveXML();
// Save as file
$xml->save('xml-import.xml'); // save as file
?>
上面提到的代码输出以下XML结构:
<channel>
<item>
<title>
<![CDATA[ pablo1 ]]>
</title>
<description>
<![CDATA[ this is description 1 ]]>
</description>
<link>
<![CDATA[ http://www.link1.com ]]>
</link>
</item>
</channel>
有人知道如何更新代码以输出以下XML结构?基本上我需要添加rss version =“2.0”行。
<rss version="2.0">
<channel>
<item>
<title>
<![CDATA[ pablo1 ]]>
</title>
<description>
<![CDATA[ this is description 1 ]]>
</description>
<link>
<![CDATA[ http://www.link1.com ]]>
</link>
</item>
</channel>
</rss>
谢谢大家的帮助!
答案 0 :(得分:0)
你可以嵌套元素......
$root = $xml->createElement('channel');
$rss = $xml->createElement('rss');
$rss->setAttribute("version","2.0");
$rss->appendChild($root);
$xml->appendChild($rss);