What is the most efficient way to retrieve the page title using cURL in PHP?
When using cURL in PHP to retrieve a webpage, you can efficiently extract the page title by using regular expressions to match the <title> tag in the HTML response. This allows you to quickly extract the title without parsing the entire HTML document.
<?php
$url = "https://example.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if(curl_errno($ch)){
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
if(preg_match("/<title>(.*?)<\/title>/i", $response, $matches)){
$title = $matches[1];
echo "Page title: " . $title;
} else {
echo "Title not found";
}
?>
Keywords
Related Questions
- How can you extract specific elements from a multidimensional array in PHP?
- What are some best practices for handling image uploads and displaying images in PHP scripts?
- In what situations might it be necessary to use a custom function like cleanID to sanitize data for generating HTML elements in PHP?