Get value of the SRC attribute of an image in a string II [closed]

0

Dear Anderson, after studying your code in PHP and adapting it to my needs. A second question came up I'm working with objects and not as an array, if by chance there are two identical ids for different images? How to convert to array to use a foreach, and it show me the two different images of an equal id. I hope I have been clear in my question. Hugs,

    
asked by anonymous 28.10.2017 / 19:36

1 answer

2

Regarding the use of equal ids, keep in mind that ids are a way of identifying an element, and must be SINGLE for each element, so use classes that are a way of identifying a group of elements.

$htmlImagens =<<<DEMO
  <img src="/images/blog/outra-imagem-A.jpg" />
  <img class="img_blog" src="/images/blog/outra-imagem-B.jpg" />
  <img class="img_blog" src="/images/blog/cliente-ideal-voce-sabe-quem-e.jpg" />
  <img src="/images/blog/outra-imagem-C.jpg" />
  <img src="/images/blog/outra-imagem-D.jpg" />
DEMO;

$dom = new DOMDocument();
$dom->loadHTML($htmlImagens);
//fazemos um loop procurando por ocorrências da Tag “img”
foreach($dom->getElementsByTagName('img') as $image) {
    //destacamos somente aquelas com classe "img_blog"
    if(strstr($image->getAttribute('class'),'img_blog')==true){
       // o array com os src das tags img cuja classe é "img_blog"
       $images[] = $image->getAttribute('src');
    }
}
print_r($images);

See working at repl.it

Bibliography

DOMDocument

foreach

strstr

    
29.10.2017 / 03:36