Reputation: 26499
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?
Upvotes: 0
Views: 2275
Reputation: 47091
A while ago, I released an open source library named PHPPowertools/DOM-Query
, which allows you to (1) load an HTML file and then (2) select or change parts of your HTML much like you'd do it with jQuery.
Using that library, here's how you'd select the sample div for your example :
use \PowerTools\DOM_Query;
// Get file content
$htmlcode = file_get_contents('http://www.example.com/');
// Create a new DOM_Query object
$H = new DOM_Query($htmlcode);
// Find the elements that match selector "div#sample"
$s = $H->select('div#sample');
Upvotes: 0
Reputation: 9048
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);
Upvotes: 2
Reputation: 55445
I would recommend something like Simple HTML DOM, although if you are very sure of the format, you may wish to look at using regex to extract the data you want.
Upvotes: 1