【问题标题】:XML DOM PHP add a child node to root/links/linkXML DOM PHP 添加一个子节点到 root/links/link
【发布时间】:2011-08-30 14:19:33
【问题描述】:

我有一个小问题……这是我的 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>

??

我只设法使用 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!";

?>

任何帮助将不胜感激:D

【问题讨论】:

    标签: php xml dom


    【解决方案1】:
    $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!";
    

    【讨论】:

    • 谢谢卡米尔,帮了我一大忙!
    • 谢谢。这也帮助了我。
    【解决方案2】:

    XPath 用于定位 XML 文档中的节点,而不是操作树。试试$dom-&gt;appendChild($new_link)

    【讨论】:

    • 把这个放在哪里?我想不通
    猜你喜欢
    • 2018-06-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2017-01-23
    相关资源
    最近更新 更多