TDsouza
TDsouza

Reputation: 938

Simple html dom php returns empty array with find

I'm trying to pick out content from a div in an external html file. Here's the html code

<some html>
    {<div id="responseDiv" style="display:none">




    required content
    </div>
</some html>

Here's the php code I'm using

include_once('simple_html_dom.php');
$curl_h = curl_init('http://www.example.com/');

curl_setopt($curl_h, CURLOPT_HTTPHEADER,
array(
    'User-Agent: NoBrowser v0.1 beta',
)
);

curl_setopt($curl_h, CURLOPT_RETURNTRANSFER, true);

$handle = curl_exec($curl_h);

$html = str_get_html('$handle');
$ret = $html->find('div[id=DivID]'); 
   foreach ($ret as $post)
  {
    echo $post->outertext;
      }

I check around and found that $ret itself is an empty array. I have tried playing around with other div IDs etc but all to the same result. What am I doing wrong??

Upvotes: 1

Views: 1292

Answers (2)

Cedric Guindon
Cedric Guindon

Reputation: 394

Is ajax an option for you?

If so:

    $.ajax({
        type:"GET",
        url:"path/to/file.html",
        dataType:"html",
        success:function(data) {
            var out = "";
            $(data).find("#div.id.you.want.to.fetch").each(function(loop, item){
                out += $(item).html();
            });
            data = out;
            $("#responseDiv").html(data);
        },
        error:function() {
            alert("Error");
        }
    });

The .each() is there so you can use it with class instead of ID

Upvotes: 0

Marc B
Marc B

Reputation: 360702

This:

$html = str_get_html('$handle');

should be:

$html = str_get_html($handle);
                     ^--   ^-- no quotes

The ' turn it into a string, which doesn't interpolate variables. So you're feeding the literal text $, h, a, etc... as your html document, NOT the html you just retrieved via curl.

Upvotes: 2

Related Questions