PHP 取得 網頁 HTTP 內容 HTML PHP 取得 網頁 HTTP 內容 HTML
  PHP       ez      2012-06-26

本篇利用 PHP 取得某網站 HTTP 的網站內容 HTML。

建立一個 class ,例如 Http_Client.class 內容如下:

<?
class HTTP_Client
{
	var $connect	= null;
	var $ip			= null;	
	var $error		= null;
	var $errno		= null;

	function HTTP_Client ($ip, $port = 80, $timeout = 30)
	{
		if (empty($ip)) return false;
		$this->connect = fsockopen($ip, $port, $this->error, $this->errno, $timeout);
		if ($this->connect) {
			$this->ip = $ip;
		}
	}

	//POST
	function post ($path, $date)
	{
		fputs($this->connect, "POST $path HTTP/1.1\n");
		fputs($this->connect, "Host: ". $this->ip ."\n");
		fputs($this->connect, "Content-type: application/x-www-form-urlencoded\n");
		fputs($this->connect, "Content-length: ". strlen($date) ."\n");
		fputs($this->connect, "User-Agent: MSIE\n");
		fputs($this->connect, "Connection: close\n\n");
		fputs($this->connect, "$date");		

		while (!feof($this->connect)) {
			$buffer .= fgets($this->connect,128);
		}
		return $buffer;
	}

	//GET
	function get ($path = "/", $arraydata = array())
	{
		if (is_array($arraydata)) {
			foreach ($arraydata as $var => $value) {
				$data .= (++$i==1) ? "$var=$value" : "&$var=$value";
			}
		} else {
			return false;
		}

		if ($data) $path .= "$data";

		fputs($this->connect, "GET $path HTTP/1.1\n");
		fputs($this->connect, "Host: ". $this->ip ."\n");
		fputs($this->connect, "User-Agent: MSIE\n");
		fputs($this->connect, "Connection: close\n\n");

		while (!feof($this->connect)) {
			$buffer .= fgets($this->connect,128);
		}
		return $buffer;
	}

	//Clear Title
	function clear($data)
	{
		$dataArray = split("\r\n\r\n",$data);
		return str_replace($dataArray[0],"",$data);
	}

	//關閉連線
	function close ()
	{
		return fclose ($this->connect);
	}
}
?>

使用 class 取得 www.google.com.tw 網站的 HTML 內容:

<?php
require_once 'Http_Client.class';

$http_client = &new HTTP_Client("www.google.com.tw","80","30");  //網址  port  讀取時間
$http_data = $http_client->post("/"); //網址
$http_client->close();
echo $http_client->clear($http_data);
?>

標籤:   PHP

我要留言