MicWit MicWit - 1 year ago 87
PHP Question

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. So I set up the DOM and scrape the site I am getting the template from:

$dom = new DOMDocument('1.0');

then I modify the src of a script and save out the template:

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:

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?

Answer Source

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, e.g.

$pageHtml = $dom->saveHTML();
$pageHtml = preg_replace('/src="%7B%7B%20(.*?)%20%7D%7D"/', 'src="{{ $1 }}"', $pageHtml);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download