我目前正在使用以下php代码生成xml文件。它采用表单输入并将它们放入xml文件中。
我想要有多个同名的孩子。例如:
<person>
<address>
<street>streetname</street>
<streetnumber>streetnumber</streetnumber>
</address>
<address>
<street>streetname</street>
<streetnumber>streetnumber</streetnumber>
</address>
</person>
我生成xml的代码遵循这个结构;
//Add first address - working
$xml->person = "";
$xml->person->address = "";
$xml->person->address->addChild('streetname', $_POST['streetname1']);
$xml->person->address->addChild('streetnumber', $_POST['streetnumber1']);
//Attempt to add second address, doesn't work
$xml->person->address = "";
$xml->person->address->addChild('streetname', $_POST['streetname2']);
$xml->person->address->addChild('streetnumber', $_POST['streetnumber2']);
答案 0 :(得分:2)
在构建XML文档时使用变量要容易得多,也不那么冗长。然后,您可以向<address>
元素添加多个<person>
元素,如下所示......
$person = $xml->addChild('person');
$address1 = $person->addChild('address');
$address1->addChild('streetname', $_POST['streetname1']);
$address1->addChild('streetnumber', $_POST['streetnumber1']);
$address2 = $person->addChild('address');
$address2->addChild('streetname', $_POST['streetname2']);
$address2->addChild('streetnumber', $_POST['streetnumber2']);