1. When you use file_get_contents or fopen, file, readfile, and other functions to read a url, a variable named $ http_response_header is created to save the http response header, stream_get_meta_data can be used to obtain data streams opened by functions such as fopen.
2. The context parameter added in php Tutorial 5 makes these functions more flexible. Through this function, we can customize http requests or even post data.
Sample Code 1:
| The code is as follows: |
Copy code |
<? Php
$ Html = file_get_contents ('http: // www.111cn.net );
Print_r ($ http_response_header );
// Or
$ Fp = fopen ('http: // www.example.com ', 'r ');
Print_r (stream_get_meta_data ($ fp ));
Fclose ($ fp );
?> |
Sample Code 2:
| The code is as follows: |
Copy code |
<? Php
$ Data = array ('foo' => 'bar ');
$ Data = http_build_query ($ data );
$ Opts = array (
'Http' => array (
'Method' => 'post ',
'Header' => "content-type: application/x-www-form-urlencoded ".
"Content-length:". strlen ($ data )."",
'Content' => $ data
),
);
$ Context = stream_context_create ($ opts );
$ Html = file_get_contents ('http: // www.example.com ', false, $ context );
Echo $ html;
?> |
Instance 3
After the information is obtained, it is automatically output to the browser. Is there any other way to organize the obtained information and control the output content? No problem at all. In the curl_setopt () function parameter, if you want to obtain the content but do not output it, use the curlopt_returntransfer parameter and set it to a non-0 value/true !, Complete code can be found:
<? Php // create a new curl resource $ ch = curl_init (); // set url and other appropriate options curl_setopt ($ ch, curlopt_url, "http://www.google.nl/"); curl_setopt ($ ch, curlopt_returntransfer, true); // grab url, and return output $ output = curl_exec ($ ch); // close curl resource, and free up system resources curl_close ($ ch ); // replace 'Google 'with 'phpit' $ output = str_replace ('Google', 'phpit', $ o Utput); // print output echo $ output;?>