XML DOM PHP将子节点添加到root/links/link

Mas*_*345 3 php xml dom

我有一个小问题......这是我的xml:

<?xml version="1.0" encoding="UTF-8"?>
<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>
Run Code Online (Sandbox Code Playgroud)

我怎么能和另一个人说话

    <link>
        <id>5443</id>
        <href>http://www.yoursite.com</href>
    </link>
Run Code Online (Sandbox Code Playgroud)

??

我设法只使用xpath向ROOT/LINKS添加记录 - > LINK,这是代码

<?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!";

?>
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激:D

Kam*_*zic 10

$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!";
Run Code Online (Sandbox Code Playgroud)