This article mainly introduces the example of using CURL in PHP to obtain the page title. This article uses regular expressions to obtain the content in the page title, page encoding, and head tags. For more information, see
This article mainly introduces the example of using CURL in PHP to obtain the page title. This article uses regular expressions to obtain the content in the page title, page encoding, and head tags. For more information, see
A practical example of getting the page title content through PHP:
Sample Code:
The Code is as follows:
<? Php
/*
Function: ObtainContent
Parameter: $ _ POST ['url']
*/
// Set the maximum number of seconds for execution
Ini_set ("expect CT. timeout", 30 );
Set_time_limit (30 );
// Check the URL
If (! Isset ($ _ POST ['url']) | $ _ POST ['url'] = ''){
Echo "URL error ";
Exit;
}
/* Retrieve URL page data */
// Initialize CURL
$ Ch = curl_init ();
// Set the URL
Curl_setopt ($ ch, CURLOPT_URL, $ _ POST ['url']);
// Let the information obtained by curl_exec () be returned in the form of data streams rather than directly output.
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// The waiting time before the connection is initiated. If it is set to 0, no waiting
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, 0 );
// Set the maximum number of seconds for CURL execution
Curl_setopt ($ ch, CURLOPT_TIMEOUT, 30 );
// Try to get the file content
$ Store = curl_exec ($ ch );
// Check whether the file is obtained correctly
If (curl_errno ($ ch )){
Echo "unable to obtain URL data ";
// Echo curl_error ($ ch);/* Display Error Message */
Exit;
}
// Disable CURL
Curl_close ($ ch );
// Parse the HTMLSection
Preg_match ("/ (. *) <\/Head>/smUi ", $ store, $ htmlHeaders );
If (! Count ($ htmlHeaders )){
Echo "unable to parse dataSection ";
Exit;
}
// ObtainEncoding format set in meta
If (preg_match ("/ ] * Http-equiv [^>] * charset = (. *) (\ "| ')/Ui", $ htmlHeaders [1], $ results )){
$ Charset = $ results [1];
} Else {
$ Charset = "None ";
}
// Obtain Text in
If (preg_match ("/ (. *) <\/Title>/Ui ", $ htmlHeaders [1], $ htmlTitles )){
If (! Count ($ htmlTitles )){
Echo "cannot be parsed Content ";
Exit;
}
// Set Convert the text encoding format to UTF-8
If ($ charset = "None "){
$ Title = $ htmlTitles [1];
} Else {
$ Title = iconv ($ charset, "UTF-8", $ htmlTitles [1]);
}
Echo $ title;
}
,