最近需要使用xml进行一些xml文件的操作,参考了一下PHP手册中的simplexml的操作方法:
xml文件如下:
<?xml version="1.0" encoding="iso-8859-1"?>
<Template>
<PhotoObjects>
<PhotoObject>
<id>1</id>
<name>null</name>
<x>0.0257937</x>
<y>0.3936667</y>
<w>0.2783334</w>
<h>0.3050000</h>
<file>1107200917451.jpg</file>
<panx>0</panx>
<pany>-0.025772270114943</pany>
<zoom>28</zoom>
</PhotoObject>
<PhotoObject>
<id>0</id>
<name>null</name>
<x>0.6952383</x>
<y>0.3953333</y>
<w>0.2788890</w>
<h>0.3033333</h>
<file>1107200917471.jpg</file>
</PhotoObjects>
</Template>
经过如下的处理后(一些变量的值是通过$_GET[]请求发送过来的):
$xml = simplexml_load_file('/example.xml');
foreach($xml->PhotoObjects->PhotoObject as $po)
{
if ($po->id == $pId) { //add panx ,pany, zoom
$po->addChild('panx', $panx);
$po->addChild('pany', $pany);
$po->addChild('zoom', $zoom);
}
}
$newXML = $xml->asXML();
$fp = fopen('/example.xml', "w");
fwrite($fp, $newXML);
fclose($fp);
<?xml version="1.0" encoding="iso-8859-1"?>
<Template>
<PhotoObjects>
<PhotoObject>
<id>1</id>
<name>null</name>
<x>0.0257937</x>
<y>0.3936667</y>
<w>0.2783334</w>
<h>0.3050000</h>
<file>1107200917451.jpg</file>
<panx>0</panx>
<pany>-0.025772270114943</pany>
<zoom>28</zoom>
</PhotoObject>
<PhotoObject>
<id>0</id>
<name>null</name>
<x>0.6952383</x>
<y>0.3953333</y>
<w>0.2788890</w>
<h>0.3033333</h>
<file>1107200917471.jpg</file>
<panx>-0.034234654234654</panx><pany>0</pany><zoom>35</zoom></PhotoObject>
</PhotoObjects>
</Template>
因为这里需要重新把xml文件写回对应的文件,需要使用asXML()方法。