首页 > 解决方案 > 如何将特定的 json 数据加入到一个 txt 文件中

问题描述

<?php
$weatherdata = file_get_contents('http://api.openweathermap.org/data/2.5/weather?id=appkey');

file_put_contents('weatherdata.json', $weatherdata);
$decoded = json_decode($weatherdata);
file_put_contents('weatherdata_alert.txt', $decoded->weather[0]->description);
?>

我可以将 json 数据中的描述转换为标题为“weatherdata_alert.txt”的文本,但似乎无法包含字符串中的其他数据。这是期望的结果“晴朗的天空 2° Millbrook”描述为“晴朗的天空”

这是json数据

{
    "coord": {
        "lon": -78.45,
        "lat": 44.15
    },
    "weather": [{
        "id": 804,
        "main": "Clouds",
        "description": "overcast clouds",
        "icon": "04n"
    }],
    "base": "stations",
    "main": {
        "temp": 272.97,
        "feels_like": 269.29,
        "temp_min": 272.04,
        "temp_max": 274.15,
        "pressure": 1021,
        "humidity": 69
    },
    "visibility": 10000,
    "wind": {
        "speed": 1.5,
        "deg": 130
    },
    "clouds": {
        "all": 90
    },
    "dt": 1604459237,
    "sys": {
        "type": 1,
        "id": 882,
        "country": "CA",
        "sunrise": 1604404430,
        "sunset": 1604440849
    },
    "timezone": -18000,
    "id": 7804010,
    "name": "Millbrook",
    "cod": 200
}

标签: phpjsontxt

解决方案


推荐阅读