I need your help...
I have a function to manipulate the HTML element to change the image url using DOM parse. My function was working properly. Here's my code:
//Update image src with new src
function upd_img_src_in_html($html_src='', $new_src='')
{
if($html_src == '' || $new_src == ''):
return '';
endif;
$xml = new DOMDocument();
$xml->loadHTML($html_src, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$imgNodes = $xml->getElementsByTagName('img');
for ($i = $imgNodes->length - 1; $i >= 0; $i--) {
$imgNode = $imgNodes->item($i);
$image_file_names = pathinfo($imgNode->getAttribute('src'), PATHINFO_BASENAME);
if(!empty($image_file_names)):
$imgNode->setAttribute('src', $new_src.$image_file_names);
$imgNode->setAttribute('style', 'max-width:90%; margin-left:auto; margin-right:auto;');
endif;
}
return html_entity_decode($xml->saveHTML());
}
However a lot of problems come after I made this function.
No 1: result_box
already defined in Entity line 1
No. 2: unexpected line tag..
I cannot control at all the input from $html_src=''
to make it run smoothly. I've tried some effort on dealing with the problem 1 but still not success. For example I used libxml_use_internal_errors()
but still got the error.
The second problem I can not overcome it. Is it any easiest way to handle only to change image src instead of using DOMDocument()
?
The answers from expert really needed here. Please give me some advice on how to deal with these problems.
Thank you..
One way to deal with messy HTML and DOMDocument is to use the PHP tidy extension first, which will correct all the errors that are in it.