phone

How to extract images from html content in php and display excerpt

There are many ways of extracting an image from content with php, but recently I was working on a project and I wanted an easy way to extract without too much work, too much coding, that is.

The idea was to access a database and display content in excerpt form with 100px by 75px thumbnail images extracted from the content. We will use the while loop to display to display a number of articles

php image extraction getting image from content in php

// first connect to database

// then run mysql_query

$result = mysql_query(“SELECT * FROM table”);
if (!$result) {

exit (‘Error fethcing member details: ‘ . mysql_error(). ”);
}

// run while loop

while ($row = mysql_fetch_array($result)) {

$title = $row ['title'];
$link = $row ['link'];
$html = $body;

// clean text to have neatly displayed content

$body = strip_tags(trim($body));

// get image from content by performing a regular expression

if (stripos($html, '<img') !== false) {
 preg_match('/<img[^>]+>/i',$html, $matches);

foreach ($matches as $var){
echo $var;
}
} else {

// else echo an alternative image, so an image is always displayed if the article does not have one

echo ‘‘;
}

// finish getting image

// display title

echo $title’;

// display body as excerpt with only 450 characters
echo ”.substr($body, 0, strpos(“$body”, ” “, “450″)).’…’;

// div with clear for neat display of content

echo ”;
}

Grow Your Business. Call: 256-361-9080

Leave a Reply