0

私はjsonに非常に慣れておらず、この問題に約1週間取り組んできました。

phpを使用してアカウントのリストからツイートを取得し、それらを.txtファイルに保存しました

$cache = dirname(__FILE__) . '/../cache/twitter-json.txt';

$data = file_get_contents('http://api.twitter.com/1/lists/statuses.json?    slug=widget&owner_screen_name=webcodepro&count=1&page=1&per_page=8&include_rts=true&include_entities=true');    

    $cachefile = fopen($cache, 'wb');
    fwrite($cachefile,utf8_encode($data));
    fclose($cachefile);

?>

アーキテクトがフロントエンドページを構造化する方法は、json値(.txtファイルにあるもの)を.jsファイルのjson変数に格納してレンダリングする必要があるということです。

編集:それはに変更されました

$cache =_ _DIR__.'/cached.txt'; 
$data = file_get_contents('http://api.twitter.com/1/lists/statuses.json?    slug=widget&owner_screen_name=webcodepro&count=1&page=1&per_page=8&include_rts=true&include_entities=true'); 

file_put_contents($cache, $data);

ファイルは空になります。何が問題なのか知っていますか?

.txtファイルの内容を.jsファイルのjson変数に保存することは可能ですか?

4

2 に答える 2

3
  1. utf8_encodeJSONはすでにUTF-8であるため、何もする必要はありません
  2. 簡単に使用できますfile_put_contents
  3. file_put_contents($cache, 'var myvar = '.$data.';');

-編集
-私の解決策を明確にするためのコード:

$cache = __DIR__.'/cached.txt';
$data = file_get_contents('http://api.twitter.com/1/lists/statuses.json?slug=widget&owner_screen_name=webcodepro&count=1&page=1&per_page=8&include_rts=true&include_entities=true');
file_put_contents($cache, 'var mydata = '.$data.';');
于 2012-07-09T12:45:04.513 に答える
1

.txtファイルの内容を.jsファイルのjson変数に保存することは可能ですか?

はい、可能です:

$txtFile  = '/path/to/txt-file.txt';
$jsFile   = '/path/to/js-file.js';
$jsPlate  = "var jsVariable = %s;\n";

$string   = file_get_contents($txtFile);
if (FALSE === $string) {
    throw new RuntimeException('Failed to load text-file.');
}

$json     = json_encode($string);
if (FALSE === $json) {
    throw new RuntimeException('Failed to json encode string.');
}

$jsString = sprintf($jsPlate, $json);
$result   = file_put_contents($jsFile, $jsString);
if (!$result) {
    throw new RuntimeException('Failed to save javascript-file.');
}

エンコーディングチェックリスト:

  • テキストファイルはUTF-8でエンコードされています。
于 2012-07-09T15:56:25.127 に答える