通过PHP在XML文件中添加新节点 [英] adding a new node in XML file via PHP

查看:197
本文介绍了通过PHP在XML文件中添加新节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想问一个问题..我怎样才能使用php在xml中插入一个新节点.我的XML文件(questions.xml)在下面

I just wanted to ask a question .. how can i insert a new node in an xml using php. my XML file (questions.xml) is given below

<?xml version="1.0" encoding="UTF-8"?>
<Quiz>
   <topic text="Preparation for Exam">
      <subtopic text="Science" />
      <subtopic text="Maths" />
      <subtopic text="english" />
   </topic>
</Quiz>

我想添加一个具有文本"属性的新子主题",即地理".我如何使用PHP做到这一点?在此先感谢. 好吧,我的代码是

I want to add a new "subtopic" with "text" attribute, that is "geography". How can i do this using PHP? Thanks in advance though. well my code is

<?php

$xmldoc = new DOMDocument();
$xmldoc->load('questions.xml');



$root = $xmldoc->firstChild;

$newElement = $xmldoc->createElement('subtopic');
$root->appendChild($newElement);

//$ newText = $ xmldoc-> createTextNode('geology'); //$ newElement-> appendChild($ newText);

// $newText = $xmldoc->createTextNode('geology'); // $newElement->appendChild($newText);

$xmldoc->save('questions.xml');

?>

推荐答案

我将使用 SimpleXML 为此.看起来像这样:

I'd use SimpleXML for this. It would look somehow like this:

// Open and parse the XML file
$xml = simplexml_load_file("questions.xml");
// Create a child in the first topic node
$child = $xml->topic[0]->addChild("subtopic");
// Add the text attribute
$child->addAttribute("text", "geography");

您可以通过echo显示新的XML代码,也可以将其存储在文件中.

You can either display the new XML code with echo or store it in a file.

// Display the new XML code
echo $xml->asXML();
// Store new XML code in questions.xml
$xml->asXML("questions.xml");

这篇关于通过PHP在XML文件中添加新节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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