php - XML DOM PHP 添加一个子节点到 root/links/link

标签 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>

我怎样才能给别人发广告

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

??

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

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

?>

任何帮助将不胜感激: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!";

关于php - XML DOM PHP 添加一个子节点到 root/links/link,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7244693/

相关文章:

android - layout_alignParentRight 不适用于线性布局内的相对布局

PHP Dom 文档 : getting textContent ignoring script tags and comments

java dom 搜索 xml

php - phpUnderControl 的替代品 - 它是最好的吗?

php - 是否必须为表提供别名,或者在某些情况下我应该提供?

PHP 显示结果的简洁方式,没有重复的标题

php - yii2 迁移不适用

php Foreach循环仅提取最后一条记录

java - 为什么 XML 注释不应该包含隐藏命令?

html - 如何在 firebug 中遍历 HTML DOM?