dongtang7347 2014-04-24 22:03
浏览 45
已采纳

将PHP变量注入XML电子邮件模板

How can I inject PHP variables into my XML email templates?

My templates are structured like this:

<Template id="1" name="Registration">
    <![CDATA[
        <p>Dear $FullName,</p>
        <p>We would like to welcome you to oursite.  Please find your activation link below, <br />
        if you cannot click the link, please copy and paste the link into your browser.</p>
        <ul>
            <li><strong>Activation Link:</strong> <a href="http://example.com/activate/$actCode/$UserName">http://example.com/activate/$actCode/$UserName</a></li>
        </ul>
        <p>&nbsp;</p>
        <p>Thank you,<br />
        ~Kevin - our site</p>
    ]]>
</Template>

and the code I am pulling it in with is:

public function PullEmailTemplate($which, $id){
    $file = $which . '.config';
    $xml = simplexml_load_file($_SERVER['DOCUMENT_ROOT'] . '/assets/templates/' . $file, NULL, LIBXML_NOCDATA);
    $res = $xml->xpath("//Template[@id='" . $id . "']");
    return (string)$res[0]; 
}

and using it like:

$msg = PullEmailTemplate('user', 1);

Now, the email sends out successfully, but I get $FullName, $ActCode, and $UserName exactly as they are... in otherwords, the aren't outputting what they should be... for instance they should be (in order): Kevin, 12345, myuser@name.com

How can I do this?

  • 写回答

1条回答 默认 最新

  • dongpu4141 2014-04-24 22:32
    关注

    You have got a matryoshka here. The outer layer is an XML document. You already have source that reads the inner element from it. The inner element (inside the CDATA) is an HTML snippet with $name placeholders. You now need some source that replaces that placeholders without destroying the HTML.

    If $name is the extend of that template system, you could use preg_replace_callback() to match them. The pattern (\$[\w\d]+) should do.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?