Simple and clean xml manipulation in PHP(PHP中简单而干净的xml操作)
                            本文介绍了PHP中简单而干净的xml操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
我正在尝试寻找一种在 php 中轻松修改 xml 的方法.PHP 文档对于如何轻松操作 xml 非常混乱.我喜欢 SimpleXml 允许轻松查找标签/属性的方式,但它似乎不允许您轻松添加子树或替换现有的.
I'm trying to search for a way to easily modify xml in php. The PHP documentation is very confusing regarding how to easily manipulate xml. I like how SimpleXml allows for easily finding tags/attributes, but it doesn't seem to allow you to easily add child trees, or replace existing ones.
有什么建议吗?
我的用例包括:
- 查找具有特定属性的特定标签元素.
 - 替换找到的元素子树.
 - 使用从 xml 文本生成的子树.
 
推荐答案
我使用 XPATH 和 SimpleXML 来更改我的文件.一个小例子……
I use XPATH and SimpleXML to change my file. A little example...
xml文件:
<?xml version="1.0"?>
<forum uri="http://myforum.org/index.php">
    <item id="1">
        <title>First Post!!!</title>
        <link>http://myforum.org/index.php/m/1</link>
        <description>hello I'm fabio</description>
    </item>
    <item id="2">
        <title>Re: Second post!!!</title>
        <link>http://myforum.org/index.php/m/2</link>
        <description>2nd good message.</description>
    </item>
</forum>
和 PHP 处理程序:
And PHP handler:
<?php
$forum = simplexml_load_file('forum.xml');
/* some xpath EXAMPLES */   
/* catch all items in forum */
$result = $forum->xpath('/forum/item');
/* catch all links */
$result = $forum->xpath('//link');
/* search for "Re:" in title and returns the item's id */
$result = $forum->xpath('//item[contains(title, "Re:")]/@id');
/* catch > 10 length items and returns the item's title*/
$result = $forum->xpath('//item[string-length(description) > 10]/title');
$forum->item[1]->title['url']   = "http://goo.gl/";     /* this add a an attribute */
$forum->item[0]->foo            = "newnode";            /* this add content */
$forum->item[0]->foo['attrib']  = 10;                   /* this add a another value */
$forum->addChild('element_name', 'value');              /* this is a new element /*
 /* delete value */
unset($forum->item[0]);
// XML rendering
echo $forum->asXML();
                        这篇关于PHP中简单而干净的xml操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:PHP中简单而干净的xml操作
				
        
 
            
        
             猜你喜欢
        
	     - 如何定位 php.ini 文件 (xampp) 2022-01-01
 - SoapClient 设置自定义 HTTP Header 2021-01-01
 - 正确分离 PHP 中的逻辑/样式 2021-01-01
 - Mod使用GET变量将子域重写为PHP 2021-01-01
 - 带有通配符的 Laravel 验证器 2021-01-01
 - PHP Count 布尔数组中真值的数量 2021-01-01
 - Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
 - 没有作曲家的 PSR4 自动加载 2022-01-01
 - 从 PHP 中的输入表单获取日期 2022-01-01
 - Laravel 仓库 2022-01-01
 
				
				
				
				