首页 > 解决方案 > 使用 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" 的奖励值,但我做不到

标签: phpxml

解决方案


假设 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

推荐阅读