使用PHP插入新的子元素XML元素需要帮助 [英] Need Assistance With Inserting New Child XML Element With PHP

查看:102
本文介绍了使用PHP插入新的子元素XML元素需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了几个小时,没有简单的解释或演示如何将新的子元素插入XML文件,然后保存XML文件。

I've been browsing around for hours now and there is no simple explaination or demonstration of how to insert a new child element into an XML file and then save the XML file.

这是XML Tree ..(很简单)

Here is the XML Tree.. (very simple)

< book > 

    <chapter> 
        <title>Everyday Italian</title> 
        <year>2005</year> 
    </chapter> 
    <chapter> 
        <title>Harry Potter</title> 
        <year>2005</year> 
    </chapter> 
    <chapter> 
        <title>XQuery Kick Start</title> 
        <year>2003</year>   
    </chapter> 

< / book > 

...
我非常感谢任何帮助。再次回顾一下,我有一个PHP文件,它的目标是用specifieidtitle和year插入一个新的chapter,然后保存新文件(基本上覆盖了book.xml文件)

... I would deeply appreciate any help with this. Once again to recap, I have a PHP file and it its goal is to insert a new "chapter" with specifieid "title" and "year" and then save the new file (basically overwriting the book.xml file)

推荐答案

php手册中有一个例子,它提供了你需要的所有信息:
http://php.net/manual/en/domdocument.save.php

There is an example inside the php-manual which gives you all informations you need: http://php.net/manual/en/domdocument.save.php

您需要的方法:


  • DOMDocument-> load()

    //从文件加载xml

  • DOMDocument-> createElement()

    //创建一个元素节点

  • DOMDocument-> createTextNode()

    //创建一个textNode

  • DOMNode - > appendChild()

    //将一个节点附加到另一个节点

  • DOMDocument-> save()

    //将XML保存到文件中

  • DOMDocument->load()
    //load xml from a file
  • DOMDocument->createElement()
    //create a element-node
  • DOMDocument->createTextNode()
    //create a textNode
  • DOMNode->appendChild()
    //append one node to another
  • DOMDocument->save()
    //save XML into a file

<?php
  //create a document
  $doc=new DOMDocument;
  //load the file
  $doc->load('book.xml');
  //create chapter-element
  $chapter=$doc->createElement('chapter');
  //create title-element
  $title=$doc->createElement('title');
  //insert text to the title
  $title->appendChild($doc->createTextNode('new title for a new chapter'));
  //create year-element
  $year=$doc->createElement('year');
  //insert text to the year
  $year->appendChild($doc->createTextNode('new year for a new chapter'));
  //append title and year to the chapter
  $chapter->appendChild($title);  
  $chapter->appendChild($year);  
  //append the chapter to the root-element
  $doc->documentElement->appendChild($chapter);  
  //save it into the file
  $doc->save('book.xml');
?>

这篇关于使用PHP插入新的子元素XML元素需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆