This post shows how to download a web page and find all the link anchor tags in the page using PHP and the Simple HTML DOM Parser which has a jQuery like syntax selector.
PHP Simple HTML DOM Parser
The PHP Simple HTML DOM Parser makes it easy to find particular elements within an HTML page in a similar way to jQuery. It can be downloaded from http://simplehtmldom.sourceforge.net/ where there are also several examples.
Finding the <a> tags from a web page
First of all include the Simple HTML DOM Parser using either include, require, include_once or require_once:
And then load the webpage into the DOM using either the file_get_html() or str_get_html() helper functions. The filename passed to file_get_html() can either be the URL to the web page or the filename of a local file. str_get_html() takes a string instead of a filename.
Now do find() on the DOM for 'a' tags as in the following example which echos out the "href" property with a linebreak between each one:
Using www.google.com as an example the above would output this:
Notice that these are the hrefs as they appear in the HTML source, so some are relative to the current document/domain and some are absolute containing a full http:// path.
Resolving the paths
I've posted how to resolve the paths to full http:// URLs using the url_to_absolute library from Nadeau Software Consulting in my earlier post titled "Extract images from a web page with PHP and the Simple HTML DOM Parser"
I will write a standalone post about how to do this later this week, which also deals with a slight issue with the URLs returned as they are partially encoded by default using rawurlencode() which is not really ideal. This later post shows the modification needed to resolve this along with some additional examples.
Related posts:
- Allowed memory size exhausted with the PHP Simple HTML DOM Parser
- Resolving relative URLs to absolute in PHP
- Extract domain, path etc from a full url with PHP
- Extract images from a web page with PHP and the Simple HTML DOM Parser
- Get meta tags from an HTML file with PHP
- Change the user agent string in PHP
0 comments:
Post a Comment