2013-03-29 5 views
1

Twitter API를 가져 오는 json_decode에 캐시 machanism을 추가하려고합니다. 중요한 부분은 $ cache 및 if 아래의 if에 관한 것입니다.json_decode에 캐시 추가 Twitter API

<?php 
function buildBaseString($baseURI, $method, $params) 
{ 
    $r = array(); 
    ksort($params); 
    foreach($params as $key=>$value){ 
     $r[] = "$key=" . rawurlencode($value); 
    } 

    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r)); //return complete base string 
} 

function buildAuthorizationHeader($oauth) 
{ 
    $r = 'Authorization: OAuth '; 
    $values = array(); 
    foreach($oauth as $key=>$value) 
     $values[] = "$key=\"" . rawurlencode($value) . "\""; 

    $r .= implode(', ', $values); 
    return $r; 
} 

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; 

$oauth_access_token = "XXXXXXXXX"; 
$oauth_access_token_secret = "XXXXXXX"; 
$consumer_key = "XXXXXXX"; 
$consumer_secret = "XXXXXXX"; 

$oauth = array('oauth_consumer_key' => $consumer_key, 
    'oauth_nonce' => time(), 
    'oauth_signature_method' => 'HMAC-SHA1', 
    'oauth_token' => $oauth_access_token, 
    'oauth_timestamp' => time(), 
    'count' => 6, 
    'oauth_version' => '1.0'); 

$base_info = buildBaseString($url, 'GET', $oauth); 
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret); 
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true)); 
$oauth['oauth_signature'] = $oauth_signature; 


$header = array(buildAuthorizationHeader($oauth), 'Expect:'); 
$options = array(CURLOPT_HTTPHEADER => $header, 
    CURLOPT_HEADER => false, 
    CURLOPT_URL => $url . '?count=6', 
    CURLOPT_RETURNTRANSFER => true, 
    CURLOPT_SSL_VERIFYPEER => false); 

$feed = curl_init(); 
curl_setopt_array($feed, $options); 
$json = curl_exec($feed); 
curl_close($feed); 

$cache = './wp-content/themes/multiformeingegno/twitter_json/'.sha1($url).'.json'; 
     if(file_exists($cache) && filemtime($cache) > time() - 1000){ 
      // if a cache file newer than 1000 seconds exist, use it 
      $twitter_data = json_decode(file_get_contents($cache)); 
     } else { 
      $twitter_data = json_decode((file_get_contents($url))); 
      file_put_contents($cache,json_encode($twitter_data)); 
     } 


    echo "<ul style='color:#6E6E6E'>"; 
    foreach ($twitter_data as $tweet) 
    { 
     if (!empty($tweet)) { 
      $text = $tweet->text; 
      $text_in_tooltip = str_replace('"', '', $text); // replace " to avoid conflicts with title="" opening tags 
      $id = $tweet->id; 
      $time = strftime('%d %B', strtotime($tweet->created_at)); 
      $username = $tweet->user->name; 
     } 
     echo '<li><span title="'; echo $text_in_tooltip; echo '">'; echo $text . "</span><br> 
      <a href=\"http://twitter.com/"; echo $username ; echo '/status/'; echo $id ; echo '"><small>'; echo $time; echo '</small></a> - 
      <a href="http://twitter.com/intent/tweet?in_reply_to='; echo $id; echo '"><small>rispondi</small></a> - 
      <a href="http://twitter.com/intent/retweet?tweet_id='; echo $id; echo '"><small>retweet</small></a> - 
      <a href="http://twitter.com/intent/favorite?tweet_id='; echo $id; echo '"><small>preferito</small></a></li>'; 
    } 

    echo '</ul>'; 
    ?> 

불행하게도 내가 갖는 이러한 오류 :

FastCGI sent in stderr: "PHP message: PHP Warning: file_get_contents(https://api.twitter.com/1.1/statuses/user_timeline.json): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request 
in /wp-content/themes/multiformeingegno/homepage_copy.php on line 62 
PHP message: PHP Warning: file_put_contents(./wp-content/themes/multiformeingegno/twitter_json/38f925d2889d7b60d4f18c448a90ab03419721c4.json): failed to open stream: No such file or directory in /wp-content/themes/multiformeingegno/homepage_copy.php on line 63 
PHP message: PHP Warning: Invalid argument supplied for foreach() in /wp-content/themes/multiformeingegno/homepage_copy.php on line 68" while reading response header from upstream, client: 94.37.252.247, server: multiformeingegno.it, request: "GET /wp-content/themes/multiformeingegno/homepage_copy.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "multiformeingegno.it" 

답변

2

당신은 이미 JSON을 가지고 있기 때문에 완전히 불필요한 캐시 미스를 때 file_get_contents를 사용하여 트위터의 URL을 열려고하는 컬를 통해 데이터

는 ** 주석 **

$feed = curl_init(); 
curl_setopt_array($feed, $options); 
$json = curl_exec($feed); 
curl_close($feed); 

$cache = './wp-content/themes/multiformeingegno/twitter_json/'.sha1($url).'.json'; 
    if(file_exists($cache) && filemtime($cache) > time() - 1000){ 
     // if a cache file newer than 1000 seconds exist, use it 
     $twitter_data = json_decode(file_get_contents($cache)); 
    } else { 
     // ** decode the json you got from the curl request here ** 
     $twitter_data = json_decode($json); 
     file_put_contents($cache,json_encode($twitter_data)); 
    } 
+0

아래의 코드 라인 이제 트윗이를 APPE보기 ar,하지만/twitter_json/파일이 없습니다 .. FastCGI가 stderr로 전송되었습니다 : "PHP 경고 : file_put_contents (./ wp-content/themes/multiformeingegno/twitter_json/38f925d2889d7b60d4f18c448a90ab03419721c4.json) : 스트림 열기 실패 : 아니오 그러한 파일이나 디렉토리에있는 /wp-content/themes/multiformeingegno/homepage_copy.php 63 행 ", 응답 : 94.37.252.247, 서버 : multiformeingegno.it, 요청 :"GET/wp-content/themes /multiformeingegno/homepage_copy.php HTTP/1.1 ", 업스트림 :"fastcgi : // unix : /var/run/php5-fpm.sock : " – MultiformeIngegno

+0

그리고 (웹 서버가 쓸 수있는) 폴더에 대한 올바른 권한을 설정했습니다. – MultiformeIngegno

+0

파일 경로는'homepage_copy.php'가있는 폴더에 상대적입니다.'./twitter_json/'. sha1 ($ url).'.json ';'캐시 경로로 사용하십시오 – Crisp