Read and write an XML file with PHP

佐手、 提交于 2019-12-01 14:40:38
frisco

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!