我想创建基于数据库记录的xml doc我已编码这些行,但我不知道如何将父节点放入其中:
$dom = new DOMDocument("1.0");
//header("Content-Type: text/plain");
while ($row = mysql_fetch_row($dtrs)) {
//create sub toping..
$root = $dom->createElement("case");
$dom->appendChild($root);
// create child element
$caseno = $dom->createElement("caseno");
$root->appendChild($caseno);
// create text node
$caseno_text = $dom->createTextNode($row[0]);
$caseno->appendChild($caseno_text);
// create child element
$petname = $dom->createElement("petname");
$root->appendChild($petname);
// create text node
$pet_text = $dom->createTextNode($row[1]);
$petname->appendChild($pet_text);
// create child element
$resname = $dom->createElement("resname");
$root->appendChild($resname);
// create text node
$res_text = $dom->createTextNode($row[2]);
$resname->appendChild($res_text);
// create child element
$hearing = $dom->createElement("hearing");
$root->appendChild($hearing);
// create text node
$hear_text = $dom->createTextNode($row[3]);
$hearing->appendChild($hear_text);
// create child element
$status = $dom->createElement("status");
$root->appendChild($status);
// create text node
$status_text = $dom->createTextNode($row[4]);
$status->appendChild($status_text);
}
我得到这样的结果,我无法将节点放入其中
<?xml version="1.0"?> <case> <caseno>010301</caseno> <petname>ashiq</petname> <resname>state</resname> <hearing>8012-08-02</hearing> <status>P</status> </case> <caseno>010302</caseno> <petname>hussain</petname> <resname>state</resname> <hearing>8012-08-02</hearing> <status>P</status> </case>
实际上我想要这样的结果;
<?xml version="1.0"?> <stage> <case> <caseno>010301</caseno> <petname>ashiq</petname> <resname>state</resname> <hearing>8012-08-02</hearing> <status>P</status> </case> <caseno>010302</caseno> <petname>hussain</petname> <resname>state</resname> <hearing>8012-08-02</hearing> <status>P</status> </case> </stage>
请帮帮我。
答案 0 :(得分:0)
您不能拥有多个根元素。您需要在循环外部分配一个根元素,并向其追加case
个元素:
<?xml version="1.0"?>
<cases>
<case>
<caseno>010301</caseno>
<petname>ashiq</petname>
<resname>state</resname>
<hearing>8012-08-02</hearing>
<status>P</status>
</case>
<case>
<caseno>010302</caseno>
<petname>hussain</petname>
<resname>state</resname>
<hearing>8012-08-02
</hearing>
<status>P</status>
</case>
</cases>
另外,作为旁白:
Please, don't use
mysql_*
functions in new code。它们不再被维护,deprecation process已经开始了。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。