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

时间:2015-06-18 08:36:25

标签: php xml

我有一个包含常见问题解答的XML文件,但是答案的一些内容需要使用PHP函数来输出适当的内容。

如何在答案中找到占位符,并用PHP函数替换它们?理想情况下,我希望能够将设置为变量的函数在多个网站上进行更改,以便使用此代码。

XML文件(最后一个区块中的占位符,%LOCAL_NO%和%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输出

<?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 个答案:

答案 0 :(得分:1)

这似乎是preg_replace_callback的一个案例,当然在评估XML之前称为。这也确保了&#34; PHP-echoed&#34;值不会破坏XML语法。

$data = array(
    'tags' => array(
        'PREM_NO'   => '1-800-CSICOP',
    )
);

$filledXML = preg_replace_callback(
    '#%(\\w+)%#', // A-Z and underscore between %%'s
    function ($matches) use ($data) {
        switch($matches[1]) {
            case 'PREM_NO':
            case 'WHATEVER':
                return $data['tags'][$matches[1]];
            case 'YYYYMMDD':
                return date('Y-m-d');
            default:
                return '';
        }
    },
    $xmlString);

// $xml = loadXML($xmlString);
$xml = loadXML($filledXML);

这允许特殊标记(如YYYYMMDD)返回运行时计算的值以及外部。您甚至可以在$ data中包含PDO句柄,并且能够在函数内部运行SQL查询。

更简单的版本

$tags = array(
    '%PREM_NO%'    => '12345',
    '%YYYYMMDD%'   => date('Y-m-d'),
    // ... et cetera
);

$filledXML = str_replace(array_keys($tags), array_values($tags), $xmlString);

答案 1 :(得分:0)

如果你知道要匹配的字符串和之前的值(即非动态),那么你可以只进行str_replace内联。

如果它们是动态的,那么您可以从数据库(或存储它们的任何位置)获取值,然后循环遍历str_replace它们。

或者,您可以使用正则表达式,例如/(\%[a-z_]+\%)/i。为此,您可以查看preg_match_all

更新:您可以将数组用作str_replace的参数。如,

$find = array('%PREM_NO%', '%LOCAL_NO%');
$replace = array('012345', '67890');

$answer = str_replace($find, $replace, $faq->a);