使用 PHP 编辑 XML 文件



我正在尝试通过我的PHP管理面板编辑一些XML值,我该怎么办?

我已经尝试过PHP的DOMDocument,但它对我没有帮助(我正在使用PHP 5(

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<tns:database xmlns:tns="http://www.iw.com/sns/platform/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ItemSpec id="57000" type="1" rewardid="232900" function_on="1" popup="1"/>
</tns:database>

假设我想编辑 id="57000" 的 rewardid 值,但我做不到

假设XML的字符串源而不是文件(尽管执行以下操作同样容易(

$xml='<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<tns:database xmlns:tns="http://www.iw.com/sns/platform/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ItemSpec id="57000" type="1" rewardid="232900" function_on="1" popup="1"/>
</tns:database>';
$dom=new DOMDocument;
$dom->loadXML( $xml );
$xp=new DOMXPath( $dom );
$col=$xp->query('//ItemSpec[@id="57000"]');
if( $col->length > 0 ){
$attr=$dom->createAttribute('rewardid');
$attr->nodeValue='banana';
$node=$col->item(0);
$node->removeAttribute('rewardid');
$node->appendChild( $attr );
}
echo $dom->saveXML();

如果是文件源,则$dom->load( $file )末尾$dom->save( $file )

要编辑现有属性,而不是像上面那样创建一个新属性并附加它,您只需执行以下操作:

$node->setAttribute('rewardid','banana'); //etc

最新更新