drz73366 2015-06-18 08:36
浏览 29
已采纳

用PHP函数替换XML文件中的占位符

I have an XML file that contains FAQs, but some of the contents of the answers need to use PHP functions to output appropriate content.

How can I find the placeholders within the answers, and replace them with PHP functions? Ideally, I would like to be able to have the functions set as variables to be changeable across multiple websites this code would be used on.

XML File (placeholders in last block, %LOCAL_NO% and %PREM_NO%)

<?xml version="1.0" encoding="UTF-8"?>
<faqs>
    <faq>
        <category>General</category>
        <q>How old do I have to be to use your service?</q>
        <a>You must be at least 18 years of age.</a>
    </faq>
    <faq>
        <category>General</category>
        <q>How long is a psychic reading?</q>
        <a>The length of a psychic reading is completely up to you. It depends on the number and complexity of the questions you ask. The average length of a reading is 15 to 20 minutes.</a>
    </faq>
    <faq>
        <category>General</category>
        <q>Can I choose the psychic I speak with?</q>
        <a>Of course! You can choose who you would like to speak to by selecting your desired psychic's profile and following the online prompts via the online booking page, or call us on %PREM_NO% and enter their PIN, or call %LOCAL_NO% and our live receptionists will connect you to a psychic that matches your requirements!</a>
    </faq>
</faqs>

PHP output

<?php // General FAQs
$faqGeneral = $xml->xpath("/faqs/faq[category='General']");
echo "<h2>General</h2>";
foreach ($faqGeneral as $faq) { ?>
    <h3><?php echo $faq->q; ?></h3>
    <p><?php echo $faq->a; ?></p>
<?php } ?>
  • 写回答

2条回答 默认 最新

  • doubei8541 2015-06-18 08:38
    关注

    If you know the strings to match and the values before (i.e., not dynamic) then you can just do a str_replace inline.

    If they are dynamic then you can grab the values from your database (or wherever you are storing them) and then loop through and str_replace them.

    Or, you could use regex, something like /(\%[a-z_]+\%)/i. For that you can look into preg_match_all.


    Update: You can use arrays as parametera for str_replace. E.g.,

    $find = array('%PREM_NO%', '%LOCAL_NO%');
    $replace = array('012345', '67890');
    
    $answer = str_replace($find, $replace, $faq->a);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系