PHP Use Curl to get the page title example _php Tips

Source: Internet
Author: User
Tags curl

Get the actual demo of the title of the page through PHP:

Sample code:

Copy Code code as follows:

<?php
/*
function: Get the <title> content on the URL page

Parameters: $_post[' url ']
*/

Set maximum number of seconds to execute
Ini_set ("Expect.timeout", 30);
Set_time_limit (30);

Check URL
if (!isset ($_post[' url ') | | | $_post[' URL '] = = ') {
echo "URL error";
Exit
}


/* Get URL page Data * *
Initialize CURL
$ch = Curl_init ();

Set URL
curl_setopt ($ch, Curlopt_url, $_post[' URL '));
Let Curl_exec () get the information returned in the form of a data stream, rather than direct output.
curl_setopt ($ch, Curlopt_returntransfer, 1);
The time to wait before initiating the connection, and if set to 0, do not wait
curl_setopt ($ch, curlopt_connecttimeout, 0);
Set the maximum number of seconds that CURL executes
curl_setopt ($ch, Curlopt_timeout, 30);

Try to get the contents of the file
$store = curl_exec ($ch);


Check that the file is correctly obtained
if (Curl_errno ($ch)) {
echo "Cannot get URL data";
echo Curl_error ($ch);/* Display error message * *
Exit
}

Close CURL
Curl_close ($ch);


Parsing HTML Preg_match ("/if (!count ($htmlHeaders)) {
echo "Cannot parse the Exit
}

Get the encoding format for meta settings in if (Preg_match ()/<meta[^>]*http-equiv[^>]*charset= (. *) (\ |) /ui ", $htmlHeaders [1], $results)) {
$charset = $results [1];
}else{
$charset = "None";
}

Get the text in <title>
if (Preg_match ("/<title> (. *) <\/title>/ui", $htmlHeaders [1], $htmlTitles)) {
if (!count ($htmlTitles)) {
echo "Cannot parse <title> content";
Exit
}

Convert <title> text encoding format to UTF-8
if ($charset = = "None") {
$title = $htmlTitles [1];
}else{
$title =iconv ($charset, "UTF-8", $htmlTitles [1]);
}
echo $title;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.