Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function to grab all links inside a <DIV> on remote site using scrape method

Anyone has a PHP function that can grab all links inside a specific DIV on a remote site? So usage might be:

$links = grab_links($url,$divname);

And return an array I can use. Grabbing links I can figure out but not sure how to make it only do it within a specific div.

Thanks! Scott

like image 842
Scott Yu - builds stuff Avatar asked Dec 05 '25 11:12

Scott Yu - builds stuff


1 Answers

Check out PHP XPath. It will let you query a document for the contents of specific tags and so on. The example on the php site is pretty straightforward: http://php.net/manual/en/simplexmlelement.xpath.php

This following example will actually grab all of the URLs in any DIVs in a doc:

$xml = new SimpleXMLElement($docAsString);

$result = $xml->xpath('//div//a');

You can use this on well-formed HTML files, not just XML.

Good XPath reference: http://msdn.microsoft.com/en-us/library/ms256086.aspx

like image 98
Matt Wonlaw Avatar answered Dec 07 '25 23:12

Matt Wonlaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!