Question

I want to use PHP & QueryPath to find all images in a document, then modify its src like this:

I want to change

http://test.com/test/name.jpg  

to

http://example.com/xxx/name.jpg  

I can find the specific class name using

$qp2 = $qp->find('body');  

Now when I want to find all img on it to change the src:

foreach ($qp2->find('img') as $i) {
    //here change the src
}  

But when I execute

echo $qp2->html(); 

I see only last image. Where is the problem?

Was it helpful?

Solution

Like this?

foreach($qp2->find('img') as $key as $img) {
    echo $img->html();
}  

Sometimes you have to use top() or end() when you are re-using the qp object. Something like:

$qp = htmlqp($lpurl);

foreach ($qp->find('img') as $key => $img){ 
  print_r($img->attr('src'));
  $url = parse_url ($img->attr('src'));
  print_r($url);
  echo '<br/>';
  if (!isset($url['scheme']) && !isset($url['host']) && !empty($url['path'])){
    $newimg = $htmlpath . '/' . $url['path'];
    $img->end()->attr('src', $newimg);
    echo $img->html();
  }
}

foreach ($qp->top()->find('script') as $key => $script){ 
  print_r($script->attr('src'));
  $url = parse_url ($script->attr('src'));
  print_r($url);
  if (!isset($url['scheme']) && !isset($url['host']) && !empty($url['path'])){
    $newjs = $htmlpath . '/' . $url['path'];
    echo '<br/>';
    echo 'this is the modified ' . $newjs;
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top