如何使用php在xml文件中插入数据?
<?xml version="1.0" encoding="UTF-8"?>
<root></root>
这是我的 xml 文件。我想在标签之间使用 dom 方法插入更新数据。我是 php 和 Xml 技术的初学者。我成功创建并读取了该文件,但无法使用 php 在其中输入数据。
创建代码如下:-
$doc = new DOMDocument('1.0', 'UTF-8');
$ele = $doc->createElement( 'root' );
$ele->nodeValue = $uvar;
$doc->appendChild( $ele );
$test = $doc->save("$id.xml");
读取代码如下:-
$xdoc = new DOMDocument( );
$xdoc->Load("$gid.xml");
$candidate = $xdoc->getElementsByTagName('root')->item(0);
$newElement = $xdoc ->createElement('root');
$txtNode = $xdoc ->createTextNode ($root);
$newElement -> appendChild($txtNode);
$candidate -> appendChild($newElement);
$msg = $candidate->nodeValue;
有人可以帮忙插入和更新吗?谢谢你!
<?xml version="1.0" encoding="UTF-8"?>
<root></root>
This is my xml file. I want to insert-update data using the dom method in between the tags. I am a beginner in php and Xml technologies. I successfully created and read from this file but not been able to enter data in it using php.
The code for creating is as follows:-
$doc = new DOMDocument('1.0', 'UTF-8');
$ele = $doc->createElement( 'root' );
$ele->nodeValue = $uvar;
$doc->appendChild( $ele );
$test = $doc->save("$id.xml");
The code for reading is as follows:-
$xdoc = new DOMDocument( );
$xdoc->Load("$gid.xml");
$candidate = $xdoc->getElementsByTagName('root')->item(0);
$newElement = $xdoc ->createElement('root');
$txtNode = $xdoc ->createTextNode ($root);
$newElement -> appendChild($txtNode);
$candidate -> appendChild($newElement);
$msg = $candidate->nodeValue;
Can someone help out with inserting and updating. Thank You!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有时 PHP + XML 可能会有点不舒服。大多数时候,我发现这段代码很有用(根据您的情况稍微重写一下):
您可能希望扩展此代码以编写二级 XML 标记。
Sometimes PHP + XML can be a bit uncomfortable. Most of the time I find this piece of code useful (rewritten a bit for your situation):
You may want to expand this code to write second level XML tags.
我对 DOMDocument 类没有太多经验,但使用 simpleXML 对象可能更容易。接起来比较快一点。
http://us.php.net/simplexml
然后你就可以
用这个来处理多个子元素具有与处理数组相同的名称,因此您可以迭代它们,或通过索引访问它们。您还可以从文件或字符串创建 simplexml 对象。一探究竟。
i don't have much experience with the DOMDocument class, but it might be easier to work with a simpleXML object instead. it's a bit faster to pick up.
http://us.php.net/simplexml
you can then just
with this you treat multiple child elements that have the same name the same way you would treat an array so you can iterate through them, or access them by index. you can also create simplexml objects from files or strings. check it out.