我在向其父级添加xml节点时遇到了一些问题。 我收到变量$ cat,$ title和$ isbn。 我想将$ title和$ isbn解析为XML节点并将其添加到正确的类别($ cat)。 死亡(后续代码var_dump($亲本)); - >返回NULL,所以最大的问题(我认为)是我无法弄清楚如何将我的节点添加到正确的父节点,因为我无法识别它。 有什么建议吗?
XML文件:
<?xml version="1.0"?>
<books version="1.0">
<categorie name="catone" id="100">
<book title="1_WS2012" isbn="isbnone" />
<book title="1W2012DHCP" isbn="ibsntwo" />
</categorie>
<categorie title="cattwo" id="101">
<book title="2W2008R2DC" isbn="isbnthree" />
</categorie>
<categorie title="catthree" id="103">
<book title="3SBS" isbn="isbnfout=" />
</categorie>
</books>
守则:
//Get variables
$cat = "catone";
$title = "testtitle";
$isbn = "testisbn";
$xmlDoc = simplexml_load_file("books.xml");
$parent = null;
//Construct node
$childstring = "<book></book>";
$child = new SimpleXMLElement($childstring);
$child->addAttribute('title', $title);
$child->addAttribute('isbn', $isbn);
//This works (results in <book title="testtile" isbn="testisbn" />)
//Add node to correct parent
for ($i=0; $i <= sizeof($xmlDoc->categorie) -1; $i++) {
//The condition does also work
if (strtoupper($xmlDoc->categorie[$i]->attributes()->name) == strtoupper($cat))
{
//I'm stuck here
$parent = $xmlDoc->categorie[$i]->attributes()->xpath('/object/data[@type="me"]');;
$xmlDoc->$parent->addChild($child);
}
}
//Write file
file_put_contents("books.xml", $xmlDoc->asXML());
期望的结果:
<books version="1.0">
<categorie name="catone" id="100">
<book title="1_WS2012" isbn="isbnone" />
<book title="1W2012DHCP" isbn="ibsntwo" />
<book title="testtitle" isbn"testisbn" />
</categorie>
<categorie title="cattwo" id="101">
<book title="2W2008R2DC" isbn="isbnthree" />
</categorie>
<categorie title="catthree" id="103">
<book title="3SBS" isbn="isbnfout=" />
</categorie>
</books>
答案 0 :(得分:2)
首先,使用xpath
选择父级。 xpath
就像SQL for XML:
$xml = simplexml_load_string($x); // assume XML in $x
$parent = $xml->xpath("/books/categorie[@name = 'catone']")[0];
注意:对于第2行末尾的[0]
,上述代码要求PHP&gt; = 5.4。(1)
现在,添加新的<book>
及其属性:
$new = $parent->addChild("book","");
$new->addAttribute("title", "testtitle");
$new->addAttribute("isbn", "testisbn");
看到它有效:https://eval.in/131009
(1)如果您使用PHP&lt; 5.4,更新或执行:
$parent = $xml->xpath("/books/categorie[@name = 'catone']");
$parent = $parent[0];