Search code examples
phpdomdocumentsetattribute

How to setAttribute of DOMDocument element with special characters?


In an HTML block such as this:

<p>Hello: <img src="hello/foo.png" /></p>

I need to transform the URL src of the image to a Laravel storage_path link. I'm using PHP DOMDocument to transform the url like so:

$link = $a->getAttribute('src');
$pat = '#(\w+\.\w+)+(?!.*(\w+)(\.\w+)+)#';
$matches = [];
preg_match($pat, $link, $matches);
$newStr = "{{ storage_path('app/' . " . $matches[0] . ") }}";
$a->setAttribute('src', $newStr);

The problem is that the output is src="%7B%7B%20storage_path('app/'%20.%20foo.png)%20%7D%7D"

How can I keep the special characters of the src attribute?


Solution

  • You can use something like:

    $html = '<p>Hello: <img src="hello/foo.png" /></p>';
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $img = $dom->getElementsByTagName('img');
    $img->item(0)->setAttribute('src', '{{ storage_path(\'app/\' . foo.png) }}');
    #loadHTML causes a !DOCTYPE tag to be added, so remove it:
    $dom->removeChild($dom->firstChild);
    #it also wraps the code in <html><body></body></html>, so remove that:
    $dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild);
    $newImage = urldecode($dom->saveHTML());
    //<p>Hello: <img src="{{ storage_path('app/' . foo.png) }}"></p>
    

    Note: In order to output the img src as you want, you'll need to use urldecode()