Four common methods for capturing network data in PHP
This section is named fsockopen, curl and file_get_contents. Specifically, we will discuss these three methods to summarize network data input and output. I have talked a lot about fsockopen before. Next I will start to transfer it to others. Here are some common methods for capturing network data.
1. Use file_get_contents to get the content in get mode:
?
1 2 3 |
$ Url = 'HTTP: // localhost/test2.php '; $ Html = file_get_contents ($ url ); Echo $ html; |
2. Use fopen to open the url and get the content.
?
1 2 3 4 5 6 7 8 9 10 |
$ Url = 'HTTP: // localhost/test2.php '; $ Fp = fopen ($ url, 'R '); Stream_get_meta_data ($ fp ); $ Result = ''; While (! Feof ($ fp )) { $ Result. = fgets ($ fp, 1024 ); } Echo "url body: $ result "; Fclose ($ fp ); |
3. Use the file_get_contents function to obtain the url in post mode.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$ Data = array ( 'Foo' => 'bar ', 'Baz' => 'boom ', 'SITE' => 'www .jb51.net ', 'Name' => 'nowa magic '); $ Data = http_build_query ($ data ); // $ Postdata = http_build_query ($ data ); $ Options = array ( 'Http' => array ( 'Method' => 'post ', 'Header' => 'content-type: application/x-www-form-urlencoded ', 'Content' => $ data // 'Timeout' => 60*60 // timeout (unit: s) ) ); $ Url = "http: // localhost/test2.php "; $ Context = stream_context_create ($ options ); $ Result = file_get_contents ($ url, false, $ context ); Echo $ result; |
4. Before using the curl library, you may need to check whether php. ini has enabled the curl extension.
?
1 2 3 4 5 6 7 8 9 |
$ Url = 'HTTP: // localhost/test2.php? Site = jb51.net '; $ Ch = curl_init (); $ Timeout = 5; Curl_setopt ($ ch, CURLOPT_URL, $ url ); Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 ); Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout ); $ File_contents = curl_exec ($ ch ); Curl_close ($ ch ); Echo $ file_contents; |