php curl后json_decode无法显示的问题
我们都知道,一般我们在php项目中使用json_decode时,不会出现问题。如果我们要想在A页面将数据库中的数据用json形式输出,例如:http://1.xxx.com/a.php
[*]<span style="font-size:24px;"><?php
[*] $sql="select * from ad where id=1 limit 1 ";
[*] $query=mysql_query($sql);
[*] $row=mysql_fetch_array($query);
[*] $str=json_encode($row);
[*] echo $str;
[*]?></span>
结果如图:显示了正确的json数据。
然后我们在b.php中可以使用 1.curl方法;2.使用file_get_contents方法首先测试curl
[*]<span style="font-size:24px;"><?php
[*] $url="http://1.xxx.com/a.php";
[*] $ch = curl_init();
[*]<span style="white-space:pre"> </span>curl_setopt($ch, CURLOPT_URL, $url);
[*]<span style="white-space:pre"> </span>curl_setopt($ch, CURLOPT_HEADER, 0);
[*]<span style="white-space:pre"> </span>curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
[*]<span style="white-space:pre"> </span>$info=curl_exec($ch);
[*]<span style="white-space:pre"> </span>curl_close($ch);
[*]<span style="white-space:pre"> </span>echo "抓取的内容:".$info;
[*]<span style="white-space:pre"> </span>echo "<br/>下面是json_decode处理后显示的:<br/>";
[*]<span style="white-space:pre"> </span>$s=json_decode($info,true);
[*]<span style="white-space:pre"> </span>echo "<pre>";
[*]<span style="white-space:pre"> </span>print_r($s);
[*]?></span>
我们会发现,出现的了故障:
竟然json_decode后无法显示!!!这是为何?
找了一天的原因,有猿友告诉我,是因为一个bom,导致json_decode无法运行,得到的结果是null,因此提供了一个方案。
[*]<?php
[*] $url="http://1.xxx.com/a.php";
[*] $ch = curl_init();
[*] curl_setopt($ch, CURLOPT_URL, $url);
[*] curl_setopt($ch, CURLOPT_HEADER, 0);
[*] curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
[*] $info=curl_exec($ch);
[*] curl_close($ch);
[*] echo "抓取的内容:".$info;
[*] echo "<br/>下面是json_decode处理后显示的:<br/>";
[*] if(preg_match('/^\xEF\xBB\xBF/',$info))
[*] {
[*] $info = substr($info,3);
[*] }
[*] $info = json_decode(trim($info),true);
[*] echo "<pre>";
[*] print_r($info);
[*]?>
到此,问题已经得到解决。。。主要的问题可能是由于数据库内容输出时显示的是带bom格式!因此需要处理下。
页:
[1]