Search code examples
phpdomscreen-scraping

How to get specific content with PHP and DOM Document?


I have a url I want to grab. I only want a short piece of content from it. The content in question is in a div that has a ID of sample.

<div id="sample">
   Content
</div>

I can grab the file like so:

$url= file_get_contents('http://www.example.com/');

But how do I select just that sample div.

Any ideas?


Solution

  • I'd recommend using the PHP Simple HTML DOM Parser.

    Then you can do:

    $html = file_get_html('http://www.example.com/');
    $html->find('div[#sample]', 0);