我有一个现有的XML文件,我想使用PhP更改其中的某些字段。 例如,说我想改变id和pw。有关如何打开和写入某些字段的任何帮助吗?
<info>
<contact:info xmlns:contact="urn:ietf:params:xml:ns:contact-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:contact-1.0
contact-1.0.xsd">
<contact:id>reg_contact001</contact:id>
<contact:authInfo>
<contact:pw>my-password</contact:pw>
</contact:authInfo>
</contact:info>
</info>
答案 0 :(得分:1)
$xml = <<<XML
<info>
<contact:info xmlns:contact="urn:ietf:params:xml:ns:contact-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:contact-1.0 contact-1.0.xsd">
<contact:id>reg_contact001</contact:id>
<contact:authInfo>
<contact:pw>my-password</contact:pw>
</contact:authInfo>
</contact:info>
</info>
XML;
function changeXML ($xml, $params) {
// prepare xml object
$xmlObj = new SimpleXMLElement($xml);
$namespaces = $xmlObj->getNameSpaces(true);
$entry = $xmlObj->children($namespaces['contact']);
// change data
$entry->info->id = $params->id;
$entry->info->authInfo->pw = $params->pw;
return '<info>' . $entry->saveXML() . '</info>';
}
print_r($xml);
$params = new \stdClass();
$params->id = 1;
$params->pw = 'supercowpowers';
$result = changeXML($xml, $params);
print_r($result);
输出
<info>
<contact:info xmlns:contact="urn:ietf:params:xml:ns:contact-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:contact-1.0 contact-1.0.xsd">
<contact:id>reg_contact001</contact:id>
<contact:authInfo>
<contact:pw>my-password</contact:pw>
</contact:authInfo>
</contact:info>
</info>
<info>
<contact:info xmlns:contact="urn:ietf:params:xml:ns:contact-1.0" schemaLocation="urn:ietf:params:xml:ns:contact-1.0 contact-1.0.xsd">
<contact:id>1</contact:id>
<contact:authInfo>
<contact:pw>supercowpowers</contact:pw>
</contact:authInfo>
</contact:info>
</info>