我正在尝试使用PHP的SimpleXML将一些数据添加到现有的XML文件中.问题是它将所有数据添加到一行中:
<name>blah</name><class>blah</class><area>blah</area> ...
Run Code Online (Sandbox Code Playgroud)
等等.全部在一条线上.如何引入换行符?
我怎么做到这样?
<name>blah</name>
<class>blah</class>
<area>blah</area>
Run Code Online (Sandbox Code Playgroud)
我正在使用asXML()功能.
谢谢.
以下是代码:
$doc = new DomDocument('1.0');
// create root node
$root = $doc->createElement('root');
$root = $doc->appendChild($root);
$signed_values = array('a' => 'eee', 'b' => 'sd', 'c' => 'df');
// process one row at a time
foreach ($signed_values as $key => $val) {
// add node for each row
$occ = $doc->createElement('error');
$occ = $root->appendChild($occ);
// add a child node for each field
foreach ($signed_values as $fieldname => $fieldvalue) {
$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
} …Run Code Online (Sandbox Code Playgroud) 在开始之前,我知道有很多类似的问题,但请相信我,我读了所有,如果不是大多数.我尝试了一堆解决方案,但似乎都没有.我得到一个空白的"树"作为我的结果.这是我正在使用的代码.
$jSON = json_decode('array here');
function array2xml($array, $xml = false){
if($xml === false){
$xml = new SimpleXMLElement('<result/>');
}
foreach($array as $key => $value){
if(is_array($value)){
array2xml($value, $xml->addChild($key));
} else {
$xml->addChild($key, $value);
}
}
return $xml->asXML();
}
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的jSON数组.
我不确定为什么它不起作用.这是我使用该功能时的结果.
<result>
<generated_in>155ms</generated_in>
</result>
Run Code Online (Sandbox Code Playgroud)