Php file reading function

Source: Internet
Author: User

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;?>

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.