How to extract img src and alt from html using PHP?
Extraction of image attributes like ‘src’, ‘alt’, ‘height’, ‘width’ etc from a HTML page using PHP. This task can be done using the following steps.
- Loading HTML content in a variable(DOM variable).
- Selecting each image in that document.
- Selecting attribute and save it’s content to a variable.
- Output as HTML img object or as plain values as required.
Example 1: This example displays the image object as output.
<?php
function crawl_page( $url ) {
$dom = new DOMDocument( '1.0' );
@ $dom ->loadHTMLFile( $url );
$anchors = $dom -> getElementsByTagName( 'img' );
foreach ( $anchors as $element ) {
$src = $element -> getAttribute( 'src' );
$alt = $element -> getAttribute( 'alt' );
$height = $element -> getAttribute( 'height' );
$width = $element -> getAttribute( 'width' );
echo '<img src="' . $src . '" alt="' . $alt . '" height="'
. $height . '" width="' . $width . '"/>' ;
}
}
?>
|
Output:
Example 2: This example displays the attribute of an image object.
<?php
function crawl_page( $url ) {
$dom = new DOMDocument( '1.0' );
@ $dom ->loadHTMLFile( $url );
$anchors = $dom -> getElementsByTagName( 'img' );
foreach ( $anchors as $element ) {
$src = $element -> getAttribute( 'src' );
$alt = $element -> getAttribute( 'alt' );
$height = $element -> getAttribute( 'height' );
$width = $element -> getAttribute( 'width' );
echo 'src=' . $src . '<br> alt=' . $alt . '<br> height='
. $height . '<br> width=' . $width . '<hr>' ;
}
}
?>
|
Output:
Last Updated :
15 May, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...