用 PHP 读写 XML 文件 [英] Read and write an XML file with PHP

查看:32
本文介绍了用 PHP 读写 XML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XML 文件,videos.xml

I have a XML file, videos.xml,

<?xml version="1.0" encoding="ISO-8859-1" ?>

<videos>
  <video url="videos/Lillebjorn.f4v" desc="Lillebjørn" />
  <video url="videos/Storebjorn.f4v" desc="Storebjørn" />
  <video url="videos/Pegasus.f4v" desc="Pegasus" />
</videos>

我想知道,我怎样才能读取上面的文件,并添加一个新标签 <video url="" desc=""/> 用新视频的 URL 和它的描述用 PHP,然后覆盖当前 videos.xml 文件,以便使用新标签对其进行更新.

I was wondering, how can I read the file above, and add a new tag <video url="" desc="" /> with the URL of the new video and description of it with PHP, and then overwrite the current videos.xml file so that it gets updated with the new tag.

推荐答案

使用 PHP 的 DOM 函数 你可以加载和操作它.

Using PHP's DOM functions you can load and manipulate it.

您也可以使用字符串函数手动修改它,DOM 在这里可能有点矫枉过正.

Also you can modify it by hand using string functions, DOM is probably an overkill here.

假设您已将文件加载到 $xml 变量中:

Assuming you have the file loaded into the $xml var:

$pos = strpos($xml, "</videos>");

if ($pos === false) {
    $xml = substr($xml,0,$pos)."\t<video url=\"$url\" desc=\"$desc\" />".substr($xml,$pos);
}

要读写只需检查

这篇关于用 PHP 读写 XML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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