dongwo2222 2015-07-06 15:06
浏览 21
已采纳

替换xml远程文件中的值并保存[duplicate]

This question already has an answer here:

I have a remote xml file: http://my-site/my-file.xml This file has this values:

<files>

  <file>
     <unique>444444</unique>
  </file>
  <file>
     <unique>666666</unique>
  </file>
  <file>
     <unique>888888</unique>
  </file>

</files>

I need to use php to replace the value of <unique>xxxxxx</unique> to be half its value, so that the file should be change to

<files>

  <file>
     <unique>222222</unique>
  </file>
  <file>
     <unique>333333</unique>
  </file>
  <file>
     <unique>444444</unique>
  </file>

</files>

I got part of the function to open and save the file but not the find&replace code:

$xml_external_path = 'http://my-site/my-file.xml'; // THIS LINE MUST EXIST
$xml = simplexml_load_file($xml_external_path);// THIS LINE MUST EXIST

$searches = array();
$replacements = array();
foreach (....) {
    $searches[] = ....
    $replacements[] = ....
}
$newXml = simplexml_load_string( str_replace( $searches, $replacements, $xml->asXml() ) );

$newXml->asXml('new-xml.xml');// THIS LINE MUST EXIST
</div>
  • 写回答

3条回答 默认 最新

  • dongmeirang4679 2015-07-06 15:25
    关注

    you can use preg_replace_callback for a pattern:

    $txt = <<<XML
    <?xml version='1.0'?>
    <files>
      <file>
         <unique>444444</unique>
      </file>
      <file>
         <unique>666666</unique>
      </file>
      <file>
         <unique>888888</unique>
      </file>
    </files>
    XML;
    // load the xml like a text
    $xml_external_path = 'http://my-site/my-file.xml;'; 
    $txt = file_get_contents($xml_external_path);
    
    $pattern = '/<unique>(.*?)<\/unique>/';
    $response = preg_replace_callback($pattern,function($match){
        $value = intval(trim($match[1]))/2;
        return '<unique>'.$value.'</unique>';
    },$xml);
    
    $newXml = simplexml_load_string( $response );//
    $newXml->asXml('new-xml.xml');//create the xml
    
    //print_r($newXml);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输