希望写一段php代码可以快速读取json接口的数据其中一个api地址
http://api.crossref.org/journals/2314-6133/works?rows=0
数据如下:
{"status":"ok","message-type":"work-list","message-version":"1.0.0","message":{"query":{"search-terms":null,"start-index":0},"items-per-page":0,"items":[],"total-results":10747,"facets":{}}}我只需要其中 total-results":10747  这个数据因为一个页面需要读取十多条这样的json数据不知道如何快速高效的把这个数据读出来jason接口不是本站的,需要远程读取,不知道如何快速高效的读取?

解决方案 »

  1.   

    curl获取json数据,然后解析json或者正则匹配都可以,这个没什么效率问题吧?
      

  2.   

    $url = 'http://api.crossref.org/journals/2314-6133/works?rows=0';
    $s = file_get_contents($url);
    $a = json_decode($s, 1);
    echo $a['message']['total-results'];
    10747
      

  3.   

    最简单就是file_get_contents把内容获取,然后json_decode解析为数组,然后读取对应的key值<?php
    $url = 'http://api.crossref.org/journals/2314-6133/works?rows=0';
    $json = file_get_contents($url);
    $data = json_decode($json, true);
    echo $data['message']['total-results'];
    ?>
      

  4.   

    www.xttblog.com
      

  5.   

    接口不稳定的话最好加个isset 判断
      

  6.   


    求教如何设置缓存,这个接口响应比较慢。
    <?php
    $url = 'http://api.crossref.org/journals/2314-6133/works?rows=0';// cache文件
    $cache_file = 'mydata.cache';// cache超时时间
    $cache_expire = 5;// 读取cache内容
    $json = get_cache($cache_file);// cache不存在,重新读取api获取数据,并写入cache
    if(!$json){
        echo 'request API<br>';
        $json = file_get_contents($url);
        set_cache($cache_file, $json, $cache_expire);
    }else{
        echo 'request cache<br>';
    }$data = json_decode($json, true);
    echo $data['message']['total-results'];function get_cache($cache_file){
        if(file_exists($cache_file)){
            $cache = file_get_contents($cache_file);
            $cache_data = json_decode($cache, true);
            if(time()<$cache_data['expire']){
                return $cache_data['data'];
            }
        }
        return '';
    }function set_cache($cache_file, $data, $expire){
        $cache_data = json_encode(array(
            'data' => $data,
            'expire' => time()+$expire
        ));
        file_put_contents($cache_file, $cache_data, true);
    }?>