2
votes

I am new to php and was having a typical problem to pull some fields from an array generated by the following php code:

$html=file_get_html("http://www.flipkart.com/books/9781846467622");

$e = $html->getElementById("mprodimg-id");
echo $e;
$f = $e->find('img');
echo $f['data-src'];

The output array f as seen after applying var_dump($f) in the code is as follows:-

Array ( [0] => simple_html_dom_node Object ( [nodetype] => 1 [tag] => img [attr] => Array ( [onerror] => img_onerror(this); [data-error-url] => http://img1a.flixcart.com/img/book.jpg [height] => 275 [width] => 275 [data-src] => http://img7a.flixcart.com/img/622/9781846467622.jpg [src] => data:image/gif;base64,R0lGODlhAQABAJEAAAAAAP////Ly8v///yH5BAEAAAMALAAAAAABAAEAAAICVAEAOw== [onload] => lzld(this) [alt] => Buy Numbers [title] => Numbers ) [children] => Array ( ) [nodes] => Array ( )

I need to echo the value of the field "data-src". Can someone please help.

The html as seen by firebug is as follows from where i need to scrape this.

<div id="mprodimg-id" class="mprodimg">             
<img width="275" height="275" title="Numbers" alt="Buy Numbers" onload="lzld(this)" src="data:image/gif;base64,R0lGODlhAQABAJEAAAAAAP////Ly8v///yH5BAEAAAMALAAAAAABAAEAAAICVAEAOw==" data-src="http://img7a.flixcart.com/img/622/9781846467622.jpg" data-error-url="http://img1a.flixcart.com/img/book.jpg" onerror="img_onerror(this);">
</div>
1
what does file_get_html function do?Erdem Ece
It stores the url as html in $html variable.anubhav

1 Answers

2
votes

Here's a clean working example :

// includes Simple HTML DOM Parser
include "simple_html_dom.php";

$url = "http://www.flipkart.com/numbers/p/9781846467622?pid=9781846467622";

//Create a DOM object
$dom = new simple_html_dom();
// Load HTML from url
$dom->load_file($url);


// Find the wanted image using the appropriate selectors
$img = $dom->find('#mprodimg-id img', 0);


// Find succeeded
if ($img){
    echo $img->{'data-src'};
}
else
    echo "Find function failed !";


// Clear DOM object (needed essentially when using many)
$dom->clear(); 
unset($dom);

OUTPUT
======
http://img7a.flixcart.com/img/622/9781846467622.jpg

Live DEMO