【问题标题】:How to extract value from nested cURL如何从嵌套 cURL 中提取值
【发布时间】:2021-11-21 14:09:19
【问题描述】:

我正在尝试从我从外部 api 收到的 (php)cURL 响应中提取数据。我收到了如下回复。

{"result":"OK","data":{"body":{"header":"New York, New York, United States of America","query":{"destination":{"id":"1506246","value":"New York, New York, United States of America","resolvedLocation":"CITY:1506246:UNKNOWN:UNKNOWN"}},"searchResults":{"totalCount":3661,"results":[{"id":260158,"name":"Red Carpet Inn Newark/Irvington, NJ","starRating":2.0,"urls":{},"address":{"streetAddress":"100 Union Avenue","extendedAddress":"",..........

因为我想从上面提取“Red Carpet Inn Newark/Irvington”,所以我改变了下面的 php curl,但它现在不会显示任何内容。我应该怎么改?谁能告诉我它有什么问题?

<?php

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "https://xxxxxxx.rapidapi.com/locations/v2/auto-complete?query=New%20York&lang=en_US&units=km",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => [
        "x-rapidapi-host: xxxxxxxx.rapidapi.com",
        "x-rapidapi-key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    ],
]);

$response = curl_exec($curl);

// echo $response; This is origial and will show values like above.

$json = json_decode($response, TRUE);

// These are list of what I tried.   
    1.echo $json["name"];
    2.echo $json["searchResults"]["results"]["name"];
    3.
    foreach ($json['results'] as $index => $v) {
    echo $v['name'].'<br>';
    }  

【问题讨论】:

    标签: php json api curl


    【解决方案1】:

    您可以使用json_decode 创建一个数组并访问单个密钥。

    $array = json_decode($json, TRUE); 
    echo $array['whatever'];
    

    附:我对 PHP 不太了解,但在这里可以提供帮助。

    【讨论】:

    • 我一直在尝试根据您的回答我能想到的所有可能的方法,但我无法让它发挥作用。例如,我尝试了“echo $array['name'];”,但它不会显示任何值。感谢您的宝贵时间。
    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 2017-04-12
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多