使用PHP的DOMDocument时,避免使用百分比编码的href属性 [英] Avoid percent-encoding href attributes when using PHP's DOMDocument

查看:64
本文介绍了使用PHP的DOMDocument时,避免使用百分比编码的href属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能找到的关于此问题的最佳答案是使用XSLT,但我不确定如何将这些答案应用于我的问题.

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.

基本上,DOMDocument在转义传入的URL(在 href 属性中)方面做得很好,但实际上我正在使用它来构建Twig/Django样式模板,d宁愿让他们一个人呆着.这是一个具体的示例,说明了问题":

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();

输出以下内容:

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

是否可以不对 href 属性进行百分比编码?

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

如果不可能直接 ,您能提出一种简洁可靠的解决方法吗?我正在做其他处理,因此必须保留DOMDocument的用法.那么也许是前/后处理的把戏?

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?

推荐答案

我对'hack'/duct-tape解决方案不满意,但这是我目前正在解决的问题:

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);

这篇关于使用PHP的DOMDocument时,避免使用百分比编码的href属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆