Home > php教程 > PHP源码 > body text

XPath对XML文件查找及修改

PHP中文网
Release: 2016-05-25 17:13:38
Original
1493 people have browsed it

php代码:

<?php
/*
<?xml version="1.0" encoding="utf-8"?>
<article>
    <item>
        <title name="t1">11</title>
        <content>content1</content>
        <pubdate>2009-10-11</pubdate>
    </item>
    <item>
        <title name="t2">title2</title>
        <content>content2</content>
        <pubdate>2009-11-11</pubdate>
    </item>
</article>
*/
if(!function_exists(&#39;l&#39;)) {
    function l() {
        echo &#39;<br/>***********************************<br />&#39;;
    }
}
if(file_exists(&#39;test10_12.xml&#39;)) {
    $xml = simplexml_load_file(&#39;test10_12.xml&#39;);
     
    //利用xpath方法查找节点位置
    $query = $xml->xpath(&#39;//title[@name="t1"]/ancestor::item&#39;);
     
    var_dump($query);  //debug
    l();               
     
    //测试在title节点下新增子节点new
    $query[0]->title->addChild(&#39;new&#39;,&#39;new&#39;);
     
    //测试在title节点下新增属性fuck
    $query[0]->title->addAttribute(&#39;fuck&#39;,&#39;fuck you&#39;);
     
    //测试修改content节点值为hello,world
    $query[0]->content = &#39;hello,world&#39;;
     
    //不解释,你懂的
    $query[0]->asXML("10.xml");
}
/*End of PHP*/
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!