Cael
Cael

Reputation: 556

PHP to retrieve title from a webpage

I have a PHP code to retrieve the title in a webpage. However, I cannot access this specific website(fine for other website) for some reason(no respond from the server). Why is this happening to only this website? What other method should I use? I tried cURL but still can't access the webpage.

This is my code:

<?php

function page_title($url) {

    $page = @file_get_contents($url);

    if (!$page) return null;

    $matches = array();

    if (preg_match('/<title>(.*?)<\/title>/', $page, $matches)) {
        return $matches[1];
    }
    else {
        return null;
    }
}


echo page_title('http://www.alibaba.com/');

?>

It came out: Warning: file_get_contents(http://www.alibaba.com): failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in C:\xampp\htdocs\myPHP\index.php on line 16. Thanks!

Upvotes: 1

Views: 326

Answers (1)

FrenchBarbu
FrenchBarbu

Reputation: 36

You have to set user_agent

$page = file_get_contents($url,false,stream_context_create(array("http" => array("user_agent" => "any"))));

Upvotes: 2

Related Questions