douxiawei9318 2013-04-12 16:14
浏览 39
已采纳

使用.htm文件(包含XML)作为模板,然后重新保存保留原始格式

I currently have a Snom XML file (stored as filename.htm) which I need to use as a template file to produce specific individual files.

I have attempted to load the .htm using get_file_contents and DOMDocument however I either lose the tags in the document or the formatting.

Is there a way to load contents of a file, replace template placeholders then save the new file preserving the format and original spacing?

Template File

<?xml version="1.0" encoding="utf-8" ?> 
<settings>
    <phone-settings e="2">
        <user_active idx="1" perm="R">on</user_active>
        <user_realname idx="1" perm="R">{Prefix}{Suffix}</user_realname>
        <user_pname idx="1" perm="R">{Prefix}{Suffix}</user_pname>
        <user_name idx="1" perm="R">{Prefix}{Suffix}</user_name>
        <phone_name idx="1" perm="R">{Prefix}{Suffix}</phone_name>
        <user_idle_text idx="1" perm="R">{Prefix}{Suffix}</user_idle_text>

        <idle_offhook idx="1" perm="R">on</idle_offhook>
        <offhook_dial_prompt idx="1" perm="R">off</offhook_dial_prompt>
    </phone-settings>
</settings>

Required End Result

<?xml version="1.0" encoding="utf-8" ?> 
<settings>
    <phone-settings e="2">
        <user_active idx="1" perm="R">on</user_active>
        <user_realname idx="1" perm="R">Phone 001</user_realname>
        <user_pname idx="1" perm="R">Phone 001</user_pname>
        <user_name idx="1" perm="R">Phone 001</user_name>
        <phone_name idx="1" perm="R">Phone 001</phone_name>
        <user_idle_text idx="1" perm="R">Phone 001</user_idle_text>

        <idle_offhook idx="1" perm="R">on</idle_offhook>
        <offhook_dial_prompt idx="1" perm="R">off</offhook_dial_prompt>
    </phone-settings>
</settings>
  • 写回答

1条回答 默认 最新

  • duanchi6377 2013-04-12 16:19
    关注

    Assming the placeholders are unique and not used elsewhere in "non-placeholder" contexts, then a simple string operation would do the trick:

    $xml = file_get_contents('template.xml');
    $xml = str_replace('{Prefix}', 'Phone', $xml);
    $xml = str_replace('{Suffix}', '001', $xml);
    etc...
    
    file_put_contents('parsed.xml, $xml);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题