Get image src using php code

If you don’t want to use regex (regular expression) to get image src then php’s DOMDocument class is useful to get information
Please see the following example.

PHP Code

$img ='<img width="500" height="334" src="http://www.word-press-site/wp-content/uploads/2013/31/sample.jpg" class="image class name" alt="image alt text" />';
$dom = new DOMDocument();
echo "Image src :".$dom->getElementsByTagName('img')->item(0)->getAttribute('src');
echo '<br/>';
echo "Image class name :".$dom->getElementsByTagName('img')->item(0)->getAttribute('class');
echo '<br/>';
echo "Image alt text :".$dom->getElementsByTagName('img')->item(0)->getAttribute('alt');
echo '<br/>';
echo "Image width :".$dom->getElementsByTagName('img')->item(0)->getAttribute('width');
echo '<br/>';
echo "Image height :".$dom->getElementsByTagName('img')->item(0)->getAttribute('height');

Output :

Image src :http://www.word-press-site/wp-content/uploads/2013/31/sample.jpg
Image class name :image class name
Image alt text :image alt text
Image width :500
Image height :300

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s