简体   繁体   English

如何在PHP中使用带有DOMDocument节点的特殊字符的setAttribute?

[英]How do I setAttribute with special characters of a DOMDocument node in PHP?

I am trying to set up a template that will be a TWIG file using the DOM in PHP. 我正在尝试使用PHP中的DOM设置一个模板为TWIG文件。 So I set up the DOM and scrape the site I am getting the template from: 因此,我设置了DOM并抓取了要从中获取模板的网站:

$dom = new DOMDocument('1.0');
$dom->loadHTMLFile('http://theurl.com');

then I modify the src of a script and save out the template: 然后我修改脚本的src并保存模板:

foreach ($domNode->childNodes as $node) {
  $node->setAttribute('src', "{{ asset('path/to/asset.js') }}");
}
$pageHtml = $dom->saveHTML();

$pageHtml is then saved out as a TWIG file: 然后将$ pageHtml保存为TWIG文件:

file_put_contents('path/to/file.twig', $pageHtml);

When I look at this file, I now have as the script tag: 当我查看此文件时,现在有了脚本标记:

<script src="%7B%7B%20asset('path/to/asset.js')%20%7D%7D"></script>

What I need to have is: 我需要拥有的是:

<script src="{{ asset('path/to/asset.js') }}"></script>

So I somehow need to stop it doing url encoding. 所以我不知何故需要停止进行网址编码。 Any way to do this? 有什么办法吗?

I don't know of any way to avoid this percent encoding. 我不知道有什么方法可以避免这种百分比编码。

One way to solve this, could be to replace the encoded characters before saving, eg 解决此问题的一种方法是保存之前替换编码的字符,例如

$pageHtml = $dom->saveHTML();
$pageHtml = preg_replace('|="%7B%7B%20(.*?)%20%7D%7D"|', '="{{ $1 }}"', $pageHtml);

So the only answer I have at the moment is to modify $pageHtml before sending it out into the TWIG file with a preg_replace: 因此,我目前唯一的答案是修改$ pageHtml,然后再使用preg_replace将其发送到TWIG文件中:

$pageHtml = preg_replace("|=\"%7B%7B%20asset|", "=\"{{ asset", $pageHtml);
$pageHtml = preg_replace("|\)%20%7D%7D\"|", ") }}\"", $pageHtml);

The first line will replace the start asset tag and the second line the end asset and will do css, javascript and any other areas that may use an asset tag. 第一行将替换起始资产标签,第二行将终止资产,并将执行css,javascript和其他可能使用资产标签的区域。

I feel as though this is not the cleanest option, but at the moment it's the cleanest option I can find that works. 我觉得这似乎不是最干净的选择,但目前它是我可以找到的最干净的选择。 If someone can come up with a better option I will set it as the answer. 如果有人可以提出更好的选择,我将其作为答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM