使用cURL从API访问JSON

时间:2018-06-13 06:06:08

标签: php json api curl

我正在尝试学习从API检索数据。我正在访问需要POST的API,因此我正在使用cURL:

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "api-url-here",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "api_key=myapikey&format=json&logs=1&search=mykeyword", "method=JSON",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "content-type: application/x-www-form-urlencoded"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

到目前为止一切顺利。

如果我回显$response,我会获得正在搜索的关键字的JSON结果。但是如何从他们那里得到一个元素呢?

我尝试使用json_decode($response),但我收到此错误:

Catchable fatal error: Object of class stdClass could not be converted to string

1 个答案:

答案 0 :(得分:1)

我认为您可以尝试使用此

#!/usr/bin/python3
import json
import re

data = (
    """
    {
         "answer_section": " ",
         "query_type": "A",
         "authority_section": "com. 172 IN SOA a.xxxx-xxxx.net. nstld.xxxx-xxxxcom. 1526440480 1800 900 604800 86400",
         "record_code": "NXDOMAIN",
         "ip_src": "xx.xx.xx.xx",
         "response_ip": "xx.xx.xx.xx",
         "date_time": "2018-05-16T00:57:20Z",
         "checksum": "CORRECT",
         "query_name": "xx.xxxx.com.",
         "port_src": 50223,
         "question_section": "xx.xxxx.com. IN A",
         "answer_count_section": 0
    }
    """
)


json_data = json.loads(data)
print('BEFORE: ', json_data)

r = re.compile('^\s([1-2]\d\d|[1-9]\d|[1-9])\s$')


found = False
key_to_delete = None

for key, value in json_data.items():
    if value == 0:
        pass
    else:
        tmp = str(value)
        for i in range(0, len(tmp)):
            if r.match(tmp[i:i+3]):
                found = True
                key_to_delete = key
                print('FOUND 1: ', value)
            elif r.match(tmp[i:i+4]):
                found = True
                key_to_delete = key
                print('FOUND 2: ', value)
            elif r.match(tmp[i:i+5]):
                found = True
                key_to_delete = key
                print('FOUND 3: ', value)

if found:
    json_data.pop(key_to_delete)

print('RESULT: ', json_data)

而不是

$decoded=json_decode($response, true);

它会将您的$decoded = json_decode($response); 转换为数组。请注意,stdClass是数组,然后您可以根据需要使用。

使用$decoded调试对象