从curl响应中编辑json响应

时间:2013-05-09 22:26:41

标签: php json curl

<?php
$json_url = "http://openexchangerates.org/api/latest.json?app_id=xxxxx&callback=angular.callbacks._0";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $json_url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$response = curl_exec($curl);

$jsonString = json_encode($response, true);
$data=json_decode($jsonString);

echo '<pre>',print_r($data),'</pre>';

$status = curl_getinfo($curl);
curl_close($curl);

输出结果为:

angular.callbacks._0({
    "disclaimer": "xx",
    "license": "xx",
    "timestamp": 1368136869,
    "base": "USD",
    "rates": {
        "AED": 3.672819,
        "AFN": 53.209,
        "ALL": 107.953875,
        "AOA": 96.358934,
        "ARS": 5.214887,
         ....
        "XOF": 501.659003,
        "XPF": 91.114876,
        "ZMK": 5227.108333,
        "ZMW": 5.314783,
        "ZWL": 322.387247
    }
})

但我需要将此输出编辑为此输出(仅限三种速率(AED / AFN / AOA))。因此,基本上在费率部分编辑json响应。我怎么能这样做?

angular.callbacks._0({
    "disclaimer": "xx",
    "license": "xx",
    "timestamp": 1368136869,
    "base": "USD",
    "rates": {
        "AED": 3.672819,
        "AFN": 53.209,
        "AOA": 107.953875,
    }
})

3 个答案:

答案 0 :(得分:3)

$response格式不正确json

您必须从中移除不必要的部分:

$jsonString= substr($response, 21, -1);

你可以这样做:

<?php
$json_url = "http://openexchangerates.org/api/latest.json?app_id=5bf388eb6f7e40209b9418e6be44f04b&callback=angular.callbacks._0";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $json_url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$response = curl_exec($curl);

$jsonString= substr($response, 21, -1);
$data=json_decode($jsonString, true);

// Get the list of rates
$rates = $data['rates'];

$new_rates = array();
$new_rates['AED'] = $rates['AED'];
$new_rates['AFN'] = $rates['AFN'];
$new_rates['AOA'] = $rates['AOA'];

$data['rates'] = $new_rates;

echo 'angular.callbacks._0('.json_encode($data).')';

$status = curl_getinfo($curl);
curl_close($curl);  

答案 1 :(得分:3)

它正在返回jsonp的响应。您需要在客户端,而不是服务器。你可以试试:

http://openexchangerates.org/api/latest.json?app_id=xxxxx

(即省略回调)。否则,请查看他们的API,看看您是否可以不同地格式化请求,以便在没有回调的情况下接收 pure JSON。

如果你绝对不能,那么你可以剥掉坏的部分:

preg_match('/{.*}/', $response, $matches);
$json = json_decode($matches[0]);

一旦你拥有了有效的JSON,这只是unset ting的一个简单问题:

unset($json->rates->XOF);
//etc.

如果更容易,您也可以将所需的内容写入其他对象。

您可能需要查看API,看看您是否只能获得特定的费率。

答案 2 :(得分:1)

使用json_decode将JSON字符串读入PHP映射数组,只选择您需要的元素,用它们组成一个新数组,最后用json_encode重新编译它。

注意:此方法比基于正则表达式/字符串的方法更强大,因为它可以理解正在处理的内容,从而允许JSON结构中的变异,只要您需要的元素位于其位置

要选择元素,请使用:

$keep = array("AED", "AFN", "AOA");
$data["rates"] = array_intersect_key($data["rates"], array_flip($keep));