search
HomeBackend DevelopmentPHP TutorialPHP使用json为何总是报错


$res = '{

    "status": "ok", //接口状态,参考http://www.heweather.com/documents/api 
               
    "basic": {  //基本信息
        "city": "北京",  //城市名称
        "cnty": "中国",  //国家
        "id": "CN101010100",  //城市ID,参见http://www.heweather.com/documents/cn-city-list
        "lat": "39.904000",  //城市维度
        "lon": "116.391000",  //城市经度
        "update": {  //更新时间
            "loc": "2015-07-02 14:44", //当地时间
            "utc": "2015-07-02 06:46"  //UTC时间
        }
    }
}';

var_dump(json_decode($res));      //显示结果

// $json = '{"foo": 12345}';
// $obj = json_decode($json);
// print $obj->{'foo'}; // 12345
?>


抱的错都是类似syntax error, unexpected 'status' (T_STRING) in /Applications/MAMP/htdocs/testjson.php on line 5


回复讨论(解决方案)

你的代码就这些?那把json里面注释去掉。。。

你的代码就这些?那把json里面注释去掉。。。


好像去掉注释真的可以显示出来了,大概是这样的
object(stdClass)#1 (2) 
{   
["status"]=> string(2) "ok" 
["basic"]=> object(stdClass)#2 (6) 
{   
["city"]=> string(6) "北京" 
["cnty"]=> string(6) "中国" 
["id"]=> string(11) "CN101010100" 
["lat"]=> string(9) "39.904000" 
["lon"]=> string(10) "116.391000" 
["update"]=> object(stdClass)#3 (2) 
{   
["loc"]=> string(16) "2015-07-02 14:44" 
["utc"]=> string(16) "2015-07-02 06:46" 


}

排好版之后的样子,那比如说 $res = json_decode($res) 之后应该怎么提取这个数组里面的“id”的值呢

$obj->basic->id

json_decode($json, true);
出来的就是数组了

好像不行,这样没法提取单个数据值

当我从一个URL获取了json包之后,$res = curl_exec($ch);    不论怎么处理,整个json包都会展现出来,而不是我想要提取的其中某个字段

    $ch = curl_init();
    $url = 'https://api.heweather.com/x3/weather?cityid=CN101200101&key=7081f8010abe4638a86e0c4c1cfee30e';
    // 执行HTTP请求
    curl_setopt($ch , CURLOPT_URL , $url);
    curl_setopt($ch , CURLOPT_SSL_VERIFYPEER , false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = json_decode(curl_exec($ch));
    echo $res['now']['cond']['txt'];
 ?>

这段请求无法获取到需要的天气值

echo $res[key($res)][0]['now']['cond']['txt']; //多云

其实你 print_r($res); 就可以看到 now 是在第三维的

注释去掉即可

$res = '{    "status": "ok",                   "basic": {        "city": "北京",        "cnty": "中国",        "id": "CN101010100",        "lat": "39.904000",        "lon": "116.391000",        "update": {            "loc": "2015-07-02 14:44",            "utc": "2015-07-02 06:46"        }    }}';var_dump(json_decode($res));      //显示结果


object(stdClass)[1]
  public 'status' => string 'ok' (length=2)
  public 'basic' => 
    object(stdClass)[2]
      public 'city' => string '北京' (length=6)
      public 'cnty' => string '中国' (length=6)
      public 'id' => string 'CN101010100' (length=11)
      public 'lat' => string '39.904000' (length=9)
      public 'lon' => string '116.391000' (length=10)
      public 'update' => 
        object(stdClass)[3]
          public 'loc' => string '2015-07-02 14:44' (length=16)
          public 'utc' => string '2015-07-02 06:46' (length=16)


获取id可以这样写

$res = '{    "status": "ok",                   "basic": {        "city": "北京",        "cnty": "中国",        "id": "CN101010100",        "lat": "39.904000",        "lon": "116.391000",        "update": {            "loc": "2015-07-02 14:44",            "utc": "2015-07-02 06:46"        }    }}';$data = json_decode($res);      //显示结果echo $data->basic->id;


CN101010100

echo $res[key($res)][0]['now']['cond']['txt']; //多云

其实你 print_r($res); 就可以看到 now 是在第三维的


好像还是不行,刚才试了一下你这个,也不能输出任何东西 

注释去掉即可

$res = '{    "status": "ok",                   "basic": {        "city": "北京",        "cnty": "中国",        "id": "CN101010100",        "lat": "39.904000",        "lon": "116.391000",        "update": {            "loc": "2015-07-02 14:44",            "utc": "2015-07-02 06:46"        }    }}';var_dump(json_decode($res));      //显示结果


object(stdClass)[1]
  public 'status' => string 'ok' (length=2)
  public 'basic' => 
    object(stdClass)[2]
      public 'city' => string '北京' (length=6)
      public 'cnty' => string '中国' (length=6)
      public 'id' => string 'CN101010100' (length=11)
      public 'lat' => string '39.904000' (length=9)
      public 'lon' => string '116.391000' (length=10)
      public 'update' => 
        object(stdClass)[3]
          public 'loc' => string '2015-07-02 14:44' (length=16)
          public 'utc' => string '2015-07-02 06:46' (length=16)


获取id可以这样写

$res = '{    "status": "ok",                   "basic": {        "city": "北京",        "cnty": "中国",        "id": "CN101010100",        "lat": "39.904000",        "lon": "116.391000",        "update": {            "loc": "2015-07-02 14:44",            "utc": "2015-07-02 06:46"        }    }}';$data = json_decode($res);      //显示结果echo $data->basic->id;


CN101010100



麻烦看一下我7楼的代码,从中如何提取天气的txt

$ch = curl_init();$url = 'https://api.heweather.com/x3/weather?cityid=CN101200101&key=7081f8010abe4638a86e0c4c1cfee30e';// 执行HTTP请求curl_setopt($ch , CURLOPT_URL , $url);curl_setopt($ch , CURLOPT_SSL_VERIFYPEER , false);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);$res = json_decode(curl_exec($ch), true); //json_decode 要有第二个参数,这样可解析成数组echo $res[key($res)][0]['now']['cond']['txt'], PHP_EOL; //为什么要这样写,看看 print_r 的输出就知道了print_r($res);

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),