从curl获取数据以放入数组并在php中显示

时间:2018-12-15 21:31:38

标签: php curl

我需要从php中的curl中获取数据,并使其显示该数组中的所有数据。我似乎根本无法使用它。我正在尝试一会儿发言,但这似乎不起作用。就像它不是一个数组。我只需要为每个地方拉出zip_code并显示该邮政编码即可。

这是我的代码:

function remote_get_contents($url)
{
    if (function_exists('curl_get_contents') AND 
 function_exists('curl_init'))
    {
            return curl_get_contents($url);
    }
    else
    {
            return file_get_contents($url);
    }
}

function curl_get_contents($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

$url = 'URL_HIDDEN';
$object = json_decode(remote_get_contents($url));
$url2 = 'URL_HIDDEN';
$object2    = json_decode(remote_get_contents($url2));

$zip = $object->postal;
$city = $object->city;
$zips = $object2->zip_code;

echo $city ." | ". $zip . " | ". $zips ."<br />";

这是原始数据输出(我只需要显示每个zip_code)就可以更长或更短。在某些情况下,可能需要拉出50多个邮政编码。其他情况可能是1或2。

 {
  "zip_codes": [
    {
        "zip_code": "27356",
        "distance": 47.395,
        "city": "Star",
        "state": "NC"
    },
    {
        "zip_code": "27247",
        "distance": 46.972,
        "city": "Ether",
        "state": "NC"
    },
    {
        "zip_code": "27325",
        "distance": 45.174,
        "city": "Robbins",
        "state": "NC"
    },
    {
        "zip_code": "27259",
        "distance": 44.428,
        "city": "Highfalls",
        "state": "NC"
    },
    {
        "zip_code": "27330",
        "distance": 49.074,
        "city": "Sanford",
        "state": "NC"
    },
    {
        "zip_code": "27341",
        "distance": 40.783,
        "city": "Seagrove",
        "state": "NC"
    },
    {
        "zip_code": "27237",
        "distance": 46.55,
        "city": "Cumnock",
        "state": "NC"
    },
    {
        "zip_code": "28137",
        "distance": 49.68,
        "city": "Richfield",
        "state": "NC"
    },
    {
        "zip_code": "27208",
        "distance": 38.639,
        "city": "Bennett",
        "state": "NC"
    },
    {
        "zip_code": "27252",
        "distance": 41.732,
        "city": "Goldston",
        "state": "NC"
    }
 ]
 }

2 个答案:

答案 0 :(得分:0)

尝试

$object2    = json_decode(remote_get_contents($url2), true);

添加会将json转换为关联的数组 json_decode doc

答案 1 :(得分:0)

您将需要遍历多维数据。像这样...

foreach (json_decode(remote_get_contents($url2))->zip_codes as $row) {
    echo $row->city ." | ". $row->zip_code . "<br />";
}