douying0108 2013-06-14 11:01
浏览 81

json_decode处理数组和对象

Here's the function I created to grab Delicious recent bookmarks via cURL auth and then XML->JSON conversion:

<?php
// JSON URL which should be requested
$json_url = 'https://api.del.icio.us/v1/posts/recent';

$username = 'myusername';  // authentication
$password = 'mypassword';  // authentication

// Initializing curl
$ch = curl_init( $json_url );

// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password   // authentication
);

// Setting curl options
curl_setopt_array( $ch, $options );



$cache_delicious = '/BLAHBLAH/'.sha1($json_url).'.json';

    if(file_exists($cache_delicious) && filemtime($cache_delicious) > time() - 1000){
        // if a cache file newer than 1000 seconds exist, use it
        $data_delicious = file_get_contents($cache_delicious);
    } else {

        $delicious_result = simplexml_load_string(curl_exec($ch));
        $data_delicious = json_encode($delicious_result);
        file_put_contents($cache_delicious, $data_delicious);
    }

$obj = $data_delicious['post']['@attributes'];

foreach (array_slice(json_decode($data_delicious, true), 0, 5) as $obj) {
    $delicious_title = str_replace('"', '\'', $obj['description']);
    $delicious_url = htmlentities($obj['href'], ENT_QUOTES, "UTF-8");
    $output = "<li><a rel=\"external nofollow\" title=\"$delicious_title\" href=\"$delicious_url\">$delicious_title</a></li>";
    echo $output;
}
?>

Here's the JSON if I do a print_r($data_delicious);, reduced only to one entry for readability:

{
   "@attributes":{
      "tag":"",
      "user":"myusername"
   },
   "post":[
      {
         "@attributes":{
            "description":"Fastweb: fibra o VDSL? Disinformazione alla porta",
            "extended":"",
            "hash":"d00d03acd6e01e9c2e899184eab35273",
            "href":"http:\/\/storify.com\/giovannibajo\/fastweb-fibra-o-vdsl",
            "private":"no",
            "shared":"yes",
            "tag":"",
            "time":"2013-06-14T10:30:08Z"
         }
      }
   ]
}

Unfortunately there's something wrong with the variables ($delicious_title and $delicious_url) in foreach, as I get Undefined index: description and href.

  • 写回答

3条回答 默认 最新

  • dongye8110 2013-06-14 11:07
    关注

    try to catch the error by using json-last-error

    评论

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭