0

This is my xml file. I want to add a new element to all books called 'price'. I don't know how to loop through all the books and append a child in them in PHP. Please help.

<book>
<title>title 1</title>
<author>author 1</author>
</book>

<book>
<title>title 2</title>
<author>author 2</author>
</book>

Expected output:

<book>
<title>title 1</title>
<author>author 1</author>
<price>20</price>
</book>

<book>
<title>title 2</title>
<author>author 2</author>
<price>20</price>
</book>

This is what I have written so far:

            $dom = new DomDocument;

    $dom->preserveWhiteSpace = FALSE;
    $dom->loadXML($xmlFile);
    $books = $dom->getElementsByTagName('book'); // Find Books

    foreach ($books as $book) //go to each book 1 by 1
    {
        $price = $dom->createElement('price');
        $price  = $dom->appendChild($price );

        $text = $dom->createTextNode('20');
        $text = $dom->appendChild($text);
    }
     $dom->saveXML();
4

1 回答 1

2

用于操作的PHPDOM是面向对象的,不是功能/程序的。

您不会生成DOMDocument然后在任何地方使用它来调用每个方法,每个节点都有自己的方法。您使用 DOMDocument 创建新元素,但之后您使用元素的方法将元素附加到另一个元素。

尝试从PHP 文档中查看以下类 DOMDocument、DOMElement、DOMAttr 和 DOMText,以及它们的共同祖先 DOMNode 。这应该可以弄清楚您正在处理哪种对象以及可以使用哪些方法。

$xmlFile = '/path/to/filename.xml';
$xmlString = file_get_contents($xmlFile);

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xmlString);
$books = $dom->getElementsByTagName('book'); // Find Books

foreach ($books as $book) //go to each book 1 by 1
{
    $price = $dom->createElement('price');
    $book->appendChild($price);

    $text = $dom->createTextNode('20');
    $price->appendChild($text);
}
$dom->saveXML();
于 2012-06-22T22:47:57.863 回答