Use PHP to Retrieve All Links on a Page

Chris Blackwell
1 min readJul 10, 2016

--

I was developing a project recently, where I had the need to get all the links on a certain page. I first turned to a JavaScript library, like Jasmine.

I really wanted to do this within my PHP code, so I ended up going with this solution:

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

$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
echo $url;
}

Originally published at Chris Blackwell’s Domain.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Chris Blackwell
Chris Blackwell

Written by Chris Blackwell

Programmer and Business owner from Canada / USA. I help businesses and entrepreneurs develop amazing digital products 🚀

No responses yet

Write a response