Tuesday, 9 February 2016

html - Extracting specific data from a web page using PHP












I would like to know if is there any way to get from a webpage a specific string of text wich is updated every now and then using PHP. I´ve searched "all over the internet" and have found nothing. Just saw that preg_match could do it, but I didn't understand how to use it.



imagine that a webpage contains this:



**GET THIS TEXT**



How can I do it using PHP, after having used file_get_contents to put the page in a variable?



Thanks in advance :)



Answer



You can use DOMDocument, like this:



$html = file_get_contents( $url);

libxml_use_internal_errors( true);
$doc = new DOMDocument;
$doc->loadHTML( $html);
$xpath = new DOMXpath( $doc);


// A name attribute on a
???
$node = $xpath->query( '//div[@name="changeable_text"]')->item( 0);

echo $node->textContent; // This will print **GET THIS TEXT**

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...