我正在尝试创建一个看起来像这样的文件
<blogs>
<blog title="Ipsum" text="Ipsum">
<photo photos=img1"/>
<photo photos=img2"/>
<photo photos=img3"/>
</blog>
<blog title="ipsum2" text="ipsum2">
<photo <photo photos=img4"/>
但由于某种原因,输出永远不会关闭节点并像这样显示xml文件
<blogs>
<blog title="Ipsum" text="Ipsum" />
<photo photos=img1"/>
<blog title="Ipsum" text="Ipsum"/>
<photo photos=img2"/>
<blog title="Ipsum" text="Ipsum"/>
<photo photos=img4"/>
<blog title="ipsum2" text="ipsum2"/>
<photo photos=img4"/>
</blogs>
这是我的功能。
$dom = new DOMDocument("1.0");
$root = $dom->createElement("blogs");
$parnode = $dom->appendChild($root);
$root = $dom->createElement("blog");
$newnode = $parnode->appendChild($root);
$photo = $dom->createElement("photo");
$parnode->appendChild($photo);
$newnode->setAttribute("title",$row['title']);
$newnode->setAttribute("text", $row['text']);
$photo->setAttribute("photos", $row['photos']);
echo $dom->saveXML();
有什么想法吗?
答案 0 :(得分:4)
您要将photo
元素附加到根blogs
而不是blog
元素
试试这段代码:
$dom = new DOMDocument("1.0");
$root = $dom->createElement("blogs");
$parnode = $dom->appendChild($root);
$root = $dom->createElement("blog");
$newnode = $parnode->appendChild($root);
$photo = $dom->createElement("photo");
$newnode->appendChild($photo); // HERE you need change $parnode to $newnode
$newnode->setAttribute("title",$row['title']);
$newnode->setAttribute("text", $row['text']);
$photo->setAttribute("photos", $row['photos']);
echo $dom->saveXML();
10个博客包含10张照片的循环的附加示例:
$dom = new DOMDocument("1.0");
$root = $dom->createElement("blogs");
$parnode = $dom->appendChild($root);
for($x = 0; $x < 10; $x++){
$root = $dom->createElement("blog");
$newnode = $parnode->appendChild($root);
for($i = 0; $i < 10; $i++){
$photo = $dom->createElement("photo");
$newnode->appendChild($photo);
$newnode->setAttribute("title",$row['title']);
$newnode->setAttribute("text", $row['text']);
$photo->setAttribute("photos", $row['photos']);
}
}
echo $dom->saveXML();