如何使用PHP附加到XML文件,最好使用SimpleXML
发布时间:2020-12-13 18:22:18 所属栏目:PHP教程 来源:网络整理
导读:我有一个 XML文件,如下所示: ?xml version="1.0" encoding="utf-8"?data config /config galleries // We have loads of these gallery gallery nameName_Here/name filepathfilepath/file.txt/filepath thumbfilepath/thumb.png/thumb /gallery /galleries
我有一个
XML文件,如下所示:
<?xml version="1.0" encoding="utf-8"?> <data> <config> </config> <galleries> // We have loads of these <gallery> <gallery> <name>Name_Here</name> <filepath>filepath/file.txt</filepath> <thumb>filepath/thumb.png</thumb> </gallery> </galleries> </data> 我一直试图弄清楚如何追加另一个<画廊>到我上面的xml文件.我尝试使用simplexml但无法使其工作,所以我在stackoverflow上尝试了这个answer以及其他bunch.但是无法让它发挥作用. $data = 'xml/config.xml'; // Load document $xml = new DOMDocument; $xml->load( $data ); #load data into the element $xpath = new DOMXPath($xml); $results = $xpath->query('/data/galleries'); $gallery_node = $results->item(0); $name_node = $xml->createElement('name'); $name_text = $xml->createTextNode('nametext'); $name_node = $name_node->appendChild($name_text); $gallery_node->appendChild($name_node); echo $xml->save($data); 我有很多失败的尝试,这应该是这么容易.基本上我想添加一个带有子名称filepath和thumb的库到同一个文件(xml / config.php). 就像我说的,我有点工作,但它没有格式化,并没有画廊标签. 题
使用SimpleXML,您可以使用
addChild() 方法.
$file = 'xml/config.xml'; $xml = simplexml_load_file($file); $galleries = $xml->galleries; $gallery = $galleries->addChild('gallery'); $gallery->addChild('name','a gallery'); $gallery->addChild('filepath','path/to/gallery'); $gallery->addChild('thumb','mythumb.jpg'); $xml->asXML($file); 请注意,SimpleXML不会为您“格式化”XML,但是从无格式的SimpleXML表示到整齐缩进的XML并不是一个复杂的步骤,这里有很多问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |