文轩网API调用脚本DEMO · PHP

文轩网API调用脚本DEMO · PHP

昨晚写的一段脚本,遇到几个问题。

通过fsockopen设置header请求文轩网API,在返回数据处理的时候,过滤掉请求头,在json正文的头尾部分有25f 和0的字符,不通的接口地址返回的数据都不一样,但是结尾都是0,可能是返回json数据造成的?得去验证一下,临时解决办法只能用substr过滤掉这个头尾的数字,但是感觉很不靠谱,如果某个返回数据不包括的话就会把有用数据截掉,为神马呢!!

另外个问题是第一次使用PHP来解析JSON,虽然在PHP下有json_encode和decode之类的函数,但是在涉及到类目等父子包含的对象时还不知道如果处理最优,空了去参考下淘宝TOP的API源码。

一直想去学习下的SMARTY..

把核心的DMEO贴出来:

apiKey = $apiKey;
		$this->apiSecret = $apiSecret;
		$this->SDK_TIMEOUT=$timeout;
	}
	
	public function getCategoryById($categoryId){
		$url = $this->CATEGORY_URL.$categoryId;
		return $this->putData($url,null);
	}
	
	public function getProductById($productId){
		$url = $this->PRODUCT_URL.$productId;
		return $this->putData($url,null);
	}
	
	public function processResult($result,$obj=null){
		$result = substr($result,5,strlen($result)-6);
		$obj = json_decode($result);
		return $obj;
	}
	
	private function isValid(){
		if($this->apiKey == '' || $this->apiSecret == ''){
			$this->processException("
请输入鉴权参数"); } } private function processException($str) { echo $str; exit(); } private function putData($url,$data){ if($this->isValid()){ return ; } $flag=0; $post=''; if($data) foreach ($data as $key=>$value) { if ($flag!=0) { $post .= "&"; $flag = 1; } $post.= $key."="; $post.= urlencode($value); $flag = 1; } $length = strlen($post); $errno = ''; $errstr = ''; $header = "GET ".$url." HTTP/1.1\r\n"; $header .= "Host:".$this->API_URL."\r\n"; $header .= "apiKey:".$this->apiKey."\r\n"; $header .= "apiSign:".md5($this->apiSecret.$this->microtime_float())."\r\n"; $header .= "apiTimestamp:".$this->microtime_float()."\r\n"; $header .= "Content-Type: application/json\r\n"; $header .= "Content-Length: ".$length."\r\n"; $header .= "Connection: Close\r\n\r\n"; $header .= $post."\r\n"; $fp = fsockopen($this->API_URL,80,$errno,$errstr,$this->SDK_TIMEOUT) or $this->processException($errstr."--->".$errno); fputs($fp,$header); $inheader = 1; $result=''; while (!feof($fp)) { $line = fgets($fp,1024); //只显示页面的返回数据 if ($inheader && ($line == "\n" || $line == "\r\n")) { $inheader = 0; } if ($inheader == 0) { $result.=$line; } } fclose($fp); return trim($result); } private function microtime_float(){ list($usec,$sec) = explode(" ", microtime()); return (((float)$usec + (float)$sec)*100).'0'; } } ?>

留下回复