Avoid percent-encoding href attributes when using PHP's DOMDocument

走远了吗. 提交于 2021-02-18 11:11:29

问题


The best answers I was able to find for this issue are using XSLT, but I'm just not sure how to apply those answers to my problem.

Basically, DOMDocument is doing a fine job of escaping URLs (in href attributes) that are passed in, but I'm actually using it to build a Twig/Django style template, and I'd rather it leave them alone. Here's a specific example, illustrating the "problem":

<?php
$doc = new DOMDocument();
$doc->loadHTML('<html><body>Test<br><a href="{{variable}}"></a></body></html>');
echo $doc->saveHTML();

Which outputs the following:

<html><body>Test<br><a href="%7B%7Bvariable%7D%7D"></a></body></html>

Is it possible to NOT percent-encode the href attribute?

If it's not possible directly, can you suggest a concise and reliable workaround? I'm doing other processing, and the DOMDocument usage will have to stay. So perhaps a pre/post processing trick?


回答1:


I'm not happy with the 'hack'/duct-tape solution, but this is how I'm currently solving the problem:

function fix_template_variable_tokens($template_string)
{
    $pattern = "/%7B%7B(\w+)%7D%7D/";
    $replacement = '{{$1}}';
    return preg_replace($pattern, $replacement, $template_string);
}

$html = $doc->saveHTML();
$html = fix_template_variable_tokens($html);


来源:https://stackoverflow.com/questions/20102346/avoid-percent-encoding-href-attributes-when-using-phps-domdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!