在PHP中格式化XML
我有一个转换成XML的数组,我为XML编写了代码。这是:在PHP中格式化XML,php,xml,Php,Xml,我有一个转换成XML的数组,我为XML编写了代码。这是: ..... $xml = new SimpleXMLElement('<?xml version="1.0"?><services></services>'); $subnode=$xml->addChild("service"); $this->array_to_xml($test_array,$subnode); $string = $xml->asXML
.....
$xml = new SimpleXMLElement('<?xml version="1.0"?><services></services>');
$subnode=$xml->addChild("service");
$this->array_to_xml($test_array,$subnode);
$string = $xml->asXML();
$result = $string;
oci_free_statement($stmt);
oci_close($this->_conn);
return $result;
}
function array_to_xml($test_array, &$xml) {
foreach($test_array as $key => $value) {
if(is_array($value)) {
$subnode = $xml->addChild("service");
$this->array_to_xml_2($value, $subnode);
}
else {
$xml->addChild("$key",htmlspecialchars("$value"));
}
}
}
public function array_to_xml_2($product, &$xml) {
foreach($product as $key => $value) {
if (is_array($value)) {
$subnode = $xml->addChild("attribute");
$this->array_to_xml($value, $subnode);
} else {
$xml->addChild(htmlspecialchars("$key"),htmlspecialchars("$value"));
}
}
}
只需删除行
$subnode=$xml->addChild(“服务”)
在$this->array\u to\u xml($test\u array,$subnode)之前
但是,如果它被删除,那么$this->array\u to\u xml($test\u array,$subnode)上的$subnode
代码>将被取消定义@封装只需传递$xml
而不是$subnode
,因为您不需要任何子节点作为启动程序
<services>
<service>
<service>
<id>1</id>
<name>INTERNET<\/name>
<attribute>
<attributeName>DOWNLOAD</attributeName>
<attributeValue>3072</attributeValue>
</attribute>
<attribute>
<attributeName>UPLOAD<\/attributeName>
<attributeValue>512<\/attributeValue>
</attribute>
</service>
<service>
<id>1<\/id>
<name>INTERNET<\/name>
<attribute>
<attributeName>DOWNLOAD<\/attributeName>
<attributeValue>5120<\/attributeValue>
</attribute>
<attribute>
<attributeName>UPLOAD<\/attributeName>
<attributeValue>1024<\/attributeValue>
</attribute>
</service>
<service>
<id>2<\/id>
<name>VOICE<\/name>
</service>
</service>
</services>
<?xml version="1.0"?>
<services>
<service>
<id>1</id>
<name>INTERNET<\/name>
<attribute>
<attributeName>DOWNLOAD</attributeName>
<attributeValue>3072</attributeValue>
</attribute>
<attribute>
<attributeName>UPLOAD<\/attributeName>
<attributeValue>512<\/attributeValue>
</attribute>
</service>
<service>
<id>1<\/id>
<name>INTERNET<\/name>
<attribute>
<attributeName>DOWNLOAD<\/attributeName>
<attributeValue>5120<\/attributeValue>
</attribute>
<attribute>
<attributeName>UPLOAD<\/attributeName>
<attributeValue>1024<\/attributeValue>
</attribute>
</service>
<service>
<id>2<\/id>
<name>VOICE<\/name>
</service>
</services>