我有一个XML属性如下:
<products>
<product ProductName="One" ProductCategory="Software::Utilities::Email">
<product ProductName="Two" ProductCategory="Software::Video::Editing">
<product ProductName="Three" ProductCategory="Software::Audio::Converter">
</products>
我怎样才能爆炸&#34; ProductCategory&#34;属性并将其分开:
<products>
<product ProductName="One" ProductCategory="Software">
<product ProductName="One" ProductCategory="Utilities">
<product ProductName="One" ProductCategory="Email">
<product ProductName="Two" ProductCategory="Software">
<product ProductName="Two" ProductCategory="Video">
<product ProductName="Two" ProductCategory="Editing">
<product ProductName="Three" ProductCategory="Software">
<product ProductName="Three" ProductCategory="Audio">
<product ProductName="Three" ProductCategory="Converter">
</products>
答案 0 :(得分:0)
你的一个例子
<?php
$string = <<<XML
<products>
<product ProductName="One" ProductCategory="Software::Utilities::Email"></product>
<product ProductName="Two" ProductCategory="Software::Video::Editing"></product>
<product ProductName="Three" ProductCategory="Software::Audio::Converter"></product>
</products>
XML;
$xml = simplexml_load_string($string);
$obj = json_decode(json_encode($xml), true);
$new_xml = '<products>';
foreach($obj['product'] as $val){
$name = $val['@attributes']['ProductName'];
$pro = explode('::', $val['@attributes']['ProductCategory']);
foreach($pro as $k=>$v){
$new_xml .= '<product ProductName="'.$name.'" ProductCategory="'.$v.'"></product>';
}
}
$new_xml .= '</products>';
$file = fopen("test.xml","w");
fwrite($file, $new_xml);
fclose($file);
?>
答案 1 :(得分:0)
您的示例XML不是有效的XML。确保关闭产品元素节点。
将源文档加载到DOM中,创建新的目标DOM。将文档元素导入目标(没有子元素)。这将创建该节点的副本。
迭代产品节点并读取ProductCategory属性,将其分解为数组。迭代数组将节点复制到目标文档中(对于每个值),将属性更改为值。
$source = new DOMDocument();
$source->loadXml($xml);
$xpath = new DOMXPath($source);
$target = new DOMDocument();
$target->formatOutput = true;
$root = $target->appendChild($target->importNode($source->documentElement));
foreach ($xpath->evaluate('/products/product') as $node) {
$list = explode('::', $node->getAttribute('ProductCategory'));
foreach ($list as $value) {
$newNode = $root->appendChild($target->importNode($node));
$newNode->setAttribute('ProductCategory', $value);
}
}
echo $target->saveXml();