1

by using PHP, I would like to get all the href and src in the image URL, where each img src will assign with each a href like this :

<a href="http://example.com/src/abc.png"><img src="http://example.com/res/bca.png"></a>

And this is the code that i already created.

$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$links = $dom->getElementsByTagName('a');
$images = $dom->getElementsByTagName('img');
$tags_links = array();
$tags_img = array();


foreach ($links as $link)
{
    $tags_links []  = $link->getAttribute('href');
}
foreach ($images as $image) 
{
    $tags_img [] = $image->getAttribute('src');
echo "<a href =\"".$url .$link->getAttribute('href')."\"><img src=\"".$url.$image->getAttribute('src')."\">"; 
}

But what i get is the last html assign with each img src

<a href ="http:../port287.html"><img src=../port2.png">

Any suggestion on how can i assign it like

<a href ="http:../port2.html"><img src=../port2.png">
<a href ="http:../port3.html"><img src=../port3.png">

1 Answer 1

1

If I'm understanding the question correctly... and its safe to assume the $html you are loading in has a 1 to 1 relation of a tags and img tags... this may work out better for you:

for ($n=0; $n < $links->length; $n++)
{
    $href = $links->item($n)->getAttribute('href');
    $src = $images->item($n)->getAttribute('src');
    echo '<a href="'. $url . $href .'"><img src="'. $url . $src .'"></a>'; 
}

This will only work if the a tags and img tags relate. Otherwise you will have some work to do to associate which href goes with which src.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.