Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - Get the first image in a page with class foo

I'm trying to get the first image with specific class from page by php

<?php
$document = new DOMDocument();
@$document->loadHTML(file_get_contents('http://www.cbsnews.com/8301-501465_162-57471379-501465/first-picture-on-the-internet-turns-20/'));
$lst = $document->getElementsByTagName('img');

for ($i=0; $i<$lst->length; $i++) {
    $image = $lst->item($i);
    echo $image->attributes->getNamedItem('src')->value, '<br />';
}
?>

this code get all images from the page, i'm trying now to get the images with class "cnet-image" from this page

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should be able to do what you need to with Simple HTML Dom, give it a try, I've used it for several similar things including image crawlers. http://simplehtmldom.sourceforge.net/

It looks like you should be able to use the following for what you need.

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

$ret = $html->find('img[class=foo]'); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...