开发者

Read and write an XML file with PHP

开发者 https://www.devze.com 2023-01-19 01:05 出处:网络
I have a XM开发者_如何学编程L file, videos.xml, <?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>

I have a XM开发者_如何学编程L 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>

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.


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

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

EDIT:

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);
}

To read and write just check

  • file_get_contents
  • file_put_contents


I strongly disagree with a practice of processing XML as text. Do not learn how to do it wrong, do it right from the start, and the right way to do it is to use DOM processing tools as:

SimpleXMLElement - as the name says - it's simple, or DOMDocument - but for this task SimpleXMLElement would be more than enough.

Start with $videos = simplexml_load_file('videos.xml'); You can modify video object as described in SimpleXMLElement documentation, and then write it back to XML file using file_put_contents('videos.xml', $videos->asXML());

Don't worry, SimpleXMLElement is in each PHP by default.


SimpleXML isn't included by default when using PHP5 on FreeBSD 8.* (when installed through ports anyway). Issue the commands below as root to get it installed. One sure-fire way to find out if it's installed is to make a script with phpinfo() in it and do a search within your browser for simplexml.

cd /usr/ports/textproc/php5-simplexml 
make install clean

Probably need to restart apache afterwards also.

Hope this saves someone from going bald. ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号