PHP to read the contents of the web file implementation code of fopen curl etc
- 2020-05-07 19:23:52
- OfStack
1.fopen implementation code:
2.curl implementation code:
Coding conversion function
another way to open a web page
<?php
$handle = fopen ("http://www.example.com/", "rb");
$contents = "";
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>
<?php
// right PHP 5 And higher
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
2.curl implementation code:
<?php
function _url($Date){
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, "$Date");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$contents = curl_exec($ch);
curl_close($ch);
return $contents;
}
$pageURL="http://www.baidu.com";
$contents=_url($pageURL);
?>
Coding conversion function
$html = file_get_contents("http://s.ofstack.com");
$html = iconv( "Big5", "UTF-8//IGNORE" , $html); // The conversion encoding mode is UTF8
print $html;
$htm = file("http://s.ofstack.com");
$h = "";
foreach($htm as $value)
{
$h.= iconv( "GB2312", "utf-8//IGNORE" , $value);
}
print_r($h);
another way to open a web page
<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
/* Sends an http request to www.example.com
with additional headers shown above */
$fp = fopen('http://www.baidu.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>