XML更改名称空间属性的值

时间:2016-07-01 18:08:07

标签: php xml

在将XML文档提交给EPP服务之前,我需要更改XML文档中嵌套命名空间属性的值。

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd">
   <command>
     <info>
       <host:info xmlns:host="urn:ietf:params:xml:ns:host-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:host-1.0 host-1.0.xsd">
         <host:name>ns1.example.test.example.com</host:name>
       </host:info>
     </info>
     <clTRID>NORID-14373-1207137695427775</clTRID>
   </command>
 </epp>

在上面的XML中,我需要更改host:name元素值。我使用PHP simplexml_load_string来首先修改XML模式中的值,如下所示。

 $xml = simplexml_load_string(file_get_contents($fn));
 $xml->command->clTRID = GUID(); // This works perfectly
 $xml->command->info->name = 'somename'; // Does not work :)

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

使用以下代码

注意我正在回应数据供您参考,如何使用

echo $xml->command->info->children('host', true)->info->name;

我尝试过的简单代码

$xmls = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd">
   <command>
     <info>
       <host:info xmlns:host="urn:ietf:params:xml:ns:host-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:host-1.0 host-1.0.xsd">
         <host:name>ns1.example.test.example.com</host:name>
       </host:info>
     </info>
     <clTRID>NORID-14373-1207137695427775</clTRID>
   </command>
 </epp>';

 $xml = simplexml_load_string($xmls);
 $xml->command->clTRID = 'something'; // This works perfectly
 echo $xml->command->info->children('host', true)->info->name; 

 $xml->command->info->children('host', true)->info->name = 'some new name';
 echo $xml->command->info->children('host', true)->info->name;