0

我只是不明白为什么我在 foreach 中得到未定义的“post”索引。这是我用来通过 cURL 对 API 进行身份验证、获取 JSON、缓存它并使用 foreach 推断我需要的信息的函数:

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

$username = 'USERNAME';  // authentication
$password = 'PASSWORD';  // 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 = '/MY_DIR/'.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;

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

这是 JSON(如果我做 a print_r($data_delicious);):

{
   "@attributes":{
      "tag":"",
      "user":"myusername"
   },
   "post":[
      {
         "@attributes":{
            "description":"MY FEED TITLE",
            "extended":"",
            "hash":"d00d03acd6e01e9c2e899184eab35273",
            "href":"http:\/\/myurl.com\/",
            "private":"no",
            "shared":"yes",
            "tag":"",
            "time":"2013-06-13T10:30:08Z"
         }
      }
   ]
}
4

1 回答 1

0

要将json_decoded 对象作为数组访问,您已将 json_decode 的第二个参数设置为 true,否则它会创建对象而不是关联数组。

$data_delicious = json_encode($delicious_result, true);
于 2013-06-14T15:14:49.747 回答