在json文本中获得一些有趣的特征

时间:2017-11-25 11:03:38

标签: php json web-services runtime-error php-5.3

我正在调用一个返回json文本的Web服务,该文本在开头“”结束时会产生一些垃圾。任何帮助或指针赞赏。我对卷曲选项有点生疏,这是我用过的一些旧代码,因为我做了这样的工作已经有一段时间了。

当我通过浏览器调用Web服务时,我得到了很好的json文本,例如以下内容。我删除了一些值,只做了几行

{ "values": [[1511596680,3],[1511596740,2],[1511596800,0],[1511596860,6],[1511596920,0],[1511596980,0],[1511597040,0],[1511597100,0],[1511597160,0],[1511603220,0],[1511603280,0],[1511603340,0],[1511603400,0],[1511603460,0],[1511603520,0],[1511603580,0],[1511603640,0],[1511603700,0],[1511603760,0],[1511603820,0]]}

当我通过充当包装器的php页面调用时。我在它前面得到了一些废话,这阻止了php在其上调用json_decode。被叫url与我以前用来在浏览器中调用Web服务完全相同。

 {“values”:[[1511596680,3],[1511596740,2],[1511596800,0],[1511596860,6],[1511596920,0],[ 1511596980,0],[1511597040,0],[1511597100,0],[1511597160,0],[1511603220,0],[1511603280,0],[1511603340,0],[1511603400,0],[1511603460, 0],[1511603520,0],[1511603580,0],[1511603640,0],[1511603700,0],[1511603760,0],[1511603820,0]]}

我的PHP代码调用Web服务如下。我不确定$ post_string是否为空是一个问题。 url由以形式的url字符串传递的参数组成?param = val& param2 = val2等。

$contenttype = 'application/json';

$headers = array(
       'Content-Type: ' . $contenttype,
       'Content-Length: ' . strlen($post_string) /* this an empty string */
        );

/* dump of headers 

Array
(
    [0] => Content-Type: application/json
    [1] => Content-Length: 0
)
*/

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); // this is get */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if (is_array($headers)
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch); // this contains the crap at the start */

2 个答案:

答案 0 :(得分:0)

我已插入以下内容以重新发送字节顺序标记。

$ output = preg_replace(' / [\ x00- \ x1F \ x80- \ xFF] /','',$ output);

感谢以下链接

How do I remove  from the beginning of a file?

答案 1 :(得分:0)

"有趣的角色"由UTF-8 BOM引起,这意味着字符串以EF BB BF开头,表示它是以UTF-8编码的。

你可以删除这样的BOM :(在jasonhao的另一个answer中找到):

//Remove UTF8 Bom

function remove_utf8_bom($text)
{
    $bom = pack('H*','EFBBBF');
    $text = preg_replace("/^$bom/", '', $text);
    return $text;
}
相关问题