Home >Backend Development >PHP Tutorial > php怎么解析json,jsonm_decode有时可以,有时不行

php怎么解析json,jsonm_decode有时可以,有时不行

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-13 12:41:141180browse

php如何解析json,jsonm_decode有时可以,有时不行

本帖最后由 cnaaa8 于 2013-06-21 09:55:14 编辑 网页编码GB2312(“注意这点,比较重要”),代码如下
当这里关键词为"玻璃移门"时,就无法解析json,但生成的url直接通过浏览器访问就有数据,如果关键词为"手机",就可以正常解析json,file_get_contents得到的数据貌似是utf-8的格式

<br />
<br />
<?php<br />
<br />
print_r(getKwToData('玻璃移门'));//当这里关键词为"玻璃移门"时,就无法解析json,但生成的url直接通过浏览器访问就有数据,如果关键词为"手机",就可以正常解析json<br />
<br />
<br />
<br />
function getKwToData($kw,$page=1,$condition='')<br />
{<br />
<br />
	if(empty($kw)){<br />
		return false;<br />
	}<br />
	if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$kw) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$kw) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$kw) != true)<br />
	{<br />
		$kw=iconv('gbk','utf-8',$kw);<br />
	}<br />
	<br />
	$randIp='110.75.71.20';<br />
	<br />
	$url="http://".$randIp."/search_turn_page_iphone.htm?sort=".$condition."&q=".urlencode($kw)."&page=".$page."&showMode=list";<br />
<br />
<br />
	<br />
	$url=iconv('gbk','utf-8',$url);//生成的url<br />
	<br />
	$data=file_get_contents($url);//这里不管什么关键词都可以获取网页数据<br />
	<br />
	<br />
	$listItem=json_decode($data);//当这里关键词为"玻璃移门"时,就无法解析json,但生成的url直接通过浏览器访问就有数据,如果关键词为"手机",就可以正常解析json<br />
	<br />
	return $listItem->listItem;<br />
}<br />
<br />
<br />
function getLocalIp(){//获得用户ip<br />
	if(isset($_SERVER['HTTP_CLIENT_IP'])){<br />
			 $ip=$_SERVER['HTTP_CLIENT_IP'];<br />
		}elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){<br />
			 $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];<br />
		}else{<br />
			 $ip=$_SERVER['REMOTE_ADDR'];<br />
		}<br />
	return $ip;<br />
}<br />
<br />
<br />
?><br />
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn