I’m trying to parse a really simple HTML document with some xpath. There are a total of 20 images and 20 links. My only goal is to get each link applied to it’s corresponding image.
My current code below is returning each image a bunch of times. So for example, that first image, which is currently showing 20 times, has a different link applied to it with each instance. So instance #1 of image #1, has link #1 applied to it, instance #2 of image #1 has link #2 applied to it, and so on.
What I want to do is include each image once and apply the corresponding link to it, so I have 20 images, with their corresponding links applied to them. I’m pretty sure I need to combine my two foreach functions, but I’m not quite sure how to do that. Any help would be awesome, thanks guys.
foreach ( $images = $xpath->query("//div[@class='image']//a//img") as $image )
{
foreach ( $links = $xpath->query("//div[@class='image']//a") as $link )
echo "<a href='" . $link->getAttribute( 'href' ) . "'><img src='" . $image->getAttribute( 'src' ) . "'</a>", "\n";
}
Expanding on Ignacio’s idea…
First, query for all anchor elements containing images
Then, use the anchor as the context for the image search
Update
To me, this seems a much more appropriate job for an XSL transformation