php - PHP 中简单干净的 xml 操作

标签 php xml xml-parsing

我正在尝试寻找一种在 php 中轻松修改 xml 的方法。 PHP 文档对于如何轻松操作 xml 非常困惑。我喜欢 SimpleXml 允许轻松查找标签/属性的方式,但它似乎不允许您轻松添加子树或替换现有子树。

有什么使用建议吗?

我的用例包括:

  • 查找具有特定属性的特定标签元素。
  • 替换找到的元素子树。
  • 使用从 xml 文本生成的子树。

最佳答案

我使用 XPATHSimpleXML 来更改我的文件。 一个小例子...

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 处理程序:

<?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 - PHP 中简单干净的 xml 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4343402/

相关文章:

php - 在没有文件扩展名的情况下在 PHP 中获取 MIME 类型

c# - 捕获 jquery ajax 错误回调中的错误?

xml - Haxe 与 XPath 有友谊吗?

php - 通用电子邮件客户端用户代理字符串

php - 用 php domdocument 得到一个完整的表格并打印出来

html - 使用 XML 而不是 HTML 创建网页有什么优势?

python - scrapy从xml文件读取起始url,该url有 "&"

c# - 将任何 XML 文档绑定(bind)到 WPF TreeView

c# - 如何使用c#获取元素值

php - 带有数组的可变变量