基本上我有和我转换为CSV的XML文件。这很好但我需要修改它以将同一个子元素添加到每个XML父元素,然后再将其转换为CSV。我似乎只能将其添加到第一个元素,就是这样。有没有办法自动将同一个子项添加到XML文件中的所有元素?
这是XML
我有成千上万的这些。
<Item>
<product>test</product>
<Image>AC45G.jpg</Image>
</Item>
这是我的代码
<?php
$new_xml = simplexml_load_file('test.xml');
$items = $new_xml->Item;
$items->addChild('distributor', 'test');
function outputCSV($new_xml) {
$outstream = fopen("php://output", 'w');
$header=false;
foreach($new_xml as $k=>$details){
if(!$header){
fputcsv($outstream,array_keys(get_object_vars($details)));
$header=true;
}
fputcsv($outstream,get_object_vars($details));
}
fclose($outstream);
}
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=lipseys.csv");
header("Pragma: no-cache");
header("Expires: 0");
outputCSV($new_xml);
?>
答案 0 :(得分:2)
默认情况下,SimpleXML遍历SimpleXMLElement的所有子元素,因此您需要foreach
覆盖根元素(在以下示例中名为$element
而不是$new_xml
作为在你的问题中),然后将新的孩子添加到每个孩子的孩子:
// iterate over child elements
foreach ($element as $child)
{
$child->addChild('distributor', 'test');
}
与SimpleXMLElement::children()
方法的区别在于,它将使用 SimpleXMLElement
的名称空间而不是给定的名称空间(可选)在children()
方法中。
您可以通过在加载文件或实例化SimpleXMLElement时指定迭代来更改默认命名空间。另见:What are the “$ns” and “$is_prefix” parameters about?
用法示例:
$xml = simplexml_load_file('test.xml');
$items = $xml;
foreach ($items as $item) {
$item->addChild('distributor', 'test: ' . $item);
}
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=lipseys.csv");
header("Pragma: no-cache");
header("Expires: 0");
$file = new SplFileObject("php://output");
foreach (new ValuesWithHeadersIterator($items) as $values) {
$file->fputcsv($values);
}
使用的迭代器:
/**
* Class ValuesIterator
*
* Treats each iteration as being (or being cast-able) to an array
* of values.
*/
class ValuesIterator extends IteratorIterator
{
public function current() {
return (array) parent::current();
}
}
/**
* Class KeysIterator
*
* Returns keys instead of values per each ValuesIterator iteration.
*/
class KeysIterator extends ValuesIterator
{
public function current() {
return array_keys(parent::current());
}
}
/**
* Class ValuesWithHeadersIterator
*
* Same as ValuesIterator but expecting the first values
* to have keys that can be used as headers
*/
class ValuesWithHeadersIterator extends IteratorIterator
{
public function __construct(Traversable $iterator) {
$headers = new LimitIterator(new KeysIterator($iterator), 0, 1);
$values = new ValuesIterator($iterator);
$append = new AppendIterator();
$append->append($headers);
$append->append($values);
parent::__construct($append);
}
}
答案 1 :(得分:1)
也许像这样使用children()和foreach
<?php
foreach ($new_xml ->children() as $second_gen){
$second_gen->addChild('distributor', 'test');
}
?>