开发者

XML DOM PHP add a child node to root/links/link

I have a little question ... this is my xml:

<?xml version="1.0" encoding="UTF-8"开发者_如何学Go?>
<links>

    <link>
        <id>432423</id>
        <href>http://www.google.ro</href>
    </link>

    <link>
        <id>5432345</id>
        <href>http://www.youtube.com</href>
    </link>

    <link>
        <id>5443</id>
        <href>http://www.yoursite.com</href>
    </link>

</links>

How can i ad another

    <link>
        <id>5443</id>
        <href>http://www.yoursite.com</href>
    </link>

??

I managed only to add a record to ROOT/LINKS -> LINK using xpath, and here is the code

<?php

$doc = new DOMDocument();
$doc->load( 'links.xml' );


$links= $doc->getElementsByTagName("links");

$xpath = new DOMXPath($doc);
$hrefs = $xpath->evaluate("/links");

$href = $hrefs->item(0);
$item = $doc->createElement("item");

    /*HERE IS THE ISSUE...*/
    $link = $doc->createElement("id","298312800");
    $href->appendChild($link);
    $link = $doc->createElement("link","www.anysite.com");
    $href->appendChild($link);

$href->appendChild($item);

print $doc->save('links.xml');

echo "the link has been added!";

?>

Any help would be appreciated :D


$doc = new DOMDocument();

// Setting formatOutput to true will turn on xml formating so it looks nicely
// however if you load an already made xml you need to strip blank nodes if you want this to work
$doc->load('links.xml', LIBXML_NOBLANKS);
$doc->formatOutput = true;

// Get the root element "links"
$root = $doc->documentElement;

// Create new link element
$link = $doc->createElement("link");

// Create and add id to new link element
$id = $doc->createElement("id","298312800");
$link->appendChild($id);

// Create and add href to new link element
$href = $doc->createElement("href","www.anysite.com");
$link->appendChild($href);

// Append new link to root element
$root->appendChild($link);

print $doc->save('links.xml');

echo "the link has been added!";


XPath is used to locate nodes in an XML document, not to manipulate the tree. Try $dom->appendChild($new_link).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜