PHP SimpleXML - 多个 children 同名
PHP SimpleXML - Multiple children with same name
我目前正在使用以下 php 代码生成一个 xml 文件。它采用表单输入并将它们放入 xml 文件中。
我想要多个 children 同名。例如:
<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']);
在构建 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']);
我目前正在使用以下 php 代码生成一个 xml 文件。它采用表单输入并将它们放入 xml 文件中。
我想要多个 children 同名。例如:
<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']);
在构建 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']);