Get Data from a URL Using cURL in PHP | PHP Tutorial For Beginners

There are situations when you need to fetch data from a certain URL — it could be an RSS feed, a JSON response, or any HTML page. This tutorial shows you how to read content from a URL using cURL in PHP.

Fetching URL Content with cURL

<?php
$url = "http://example.com";

function file_get_contents_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER,         0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL,            $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

$html = file_get_contents_curl($url);
// $html now contains the full HTML of the page.
?>

Extracting the Page Title

If you want to read just the <title> of a URL (useful for SEO or link-preview tools), add this after retrieving $html:

<?php
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');

$title = $nodes->item(0)->nodeValue;
// $title now holds the page title string.
echo $title;
?>

cURL Options Explained

  • CURLOPT_HEADER 0 — do not include response headers in the output.
  • CURLOPT_RETURNTRANSFER 1 — return the response as a string instead of printing it.
  • CURLOPT_URL — the URL to fetch.
  • CURLOPT_FOLLOWLOCATION 1 — follow any HTTP redirects automatically.

Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.

← Older Post Newer Post →