从长字符串中获取JSON

时间:2014-01-31 19:54:20

标签: php

由于我的主持人不允许file_get_contents,我必须使用别的东西来进行API调用。 我得到了这段代码来获取网站的内容:

function get_contents_by_uri($uri) {
$uriElem = parse_url ( $uri );
$fp = @fsockopen ( $uriElem ['host'], 80, $errno, $errstr, 10 );

if (! $fp) {
    throw new Exception ( "Could not create socket: '" . $errnstr . "' (" . $errno . ")." );
}

$request = "GET " . $uriElem ['path'] . (isset ( $uriElem ['query'] ) ? "?" . $uriElem ['query'] : "") . " HTTP/1.1\r\n";
$request .= "Host: " . $uriElem ['host'] . "\r\n";
$request .= "Connection: Close\r\n\r\n";

fwrite ( $fp, $request );
$response = "";
while ( ! feof ( $fp ) ) {
    $response .= fgets ( $fp, 128 );
}
fclose ( $fp );

// split headers from data
$responseSplit = explode ( "\r\n\r\n", $response, 2 );

return $responseSplit [1];
}

这适用于这个简单的调用: http://dogechain.info/chain/Dogecoin/q/getblockcount

但它为包含JSON的调用添加了一些数据。

示例:

如果我在http://data.bter.com/api/1/ticker/doge_btc上使用get_contents_by_uri(),我就不会

{"result":"true","last":"0.00000188","high":"0.00000191","low":"0.00000185","avg":"0.00000188","sell":"0.00000189","buy":"0.00000188","vol_doge":82094227.628,"vol_btc":154.34039658}

b6 {"result":"true","last":"0.00000188","high":"0.00000191","low":"0.00000185","avg":"0.00000188","sell":"0.00000189","buy":"0.00000188","vol_doge":82094227.628,"vol_btc":154.34039658} 0

如何获得此字符串的唯一JSON部分?

1 个答案:

答案 0 :(得分:1)

我不确定为什么(到目前为止),但使用HTTP/1.0代替HTTP/1.1对我有效。
(我通过潜伏互联网并尝试其他解决方案找到了它。)