Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get src attribute of an image based on class or id

Tags:

regex

php

src

I want to get src in image based on class or id. Ex. On html page there are many <img src="url"> but only one have a class or id: <img src="url" class="image" or id="image"> How to get right src attribute wich have a specific class or id? Pls regex not dom

I gonna explain you why I dont want to use dom or other libraries because I'm getting a html page from an other site which not allow fopen or _file_get_contents or DOM but only Curl could do this. Sure I have a reason why I not use these libraries like simplehtmldom because sometimes is impossible to get remote html page and I should make by myself some scripts.

like image 932
goni Avatar asked Dec 10 '25 10:12

goni


1 Answers

You say that you don't want to use DOM libraries because you need to use cURL. That's fine -- DOMDocument and simple_xml_load_string both take string arguments. So you can get your string from cURL and load it into your DOM library.

For instance:

$html = curl_exec($ch); // assuming CURLOPT_RETURNTRANSFER

$dom = new DOMDocument;
$dom->loadHTML($html); // load the string from cURL into the DOMDocument object

// using an ID
$el = $dom->getElementById('image');

// using a class
$xpath = new DOMXPath($dom);
$els = $xpath->query('//img[@class="image"]');
$el = $els->item(0);

$src = $el->getAttribute('src');
like image 72
lonesomeday Avatar answered Dec 12 '25 01:12

lonesomeday



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!