php使用file_get_contents獲取遠程js文件

public function getBrands()
{
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' &&
        $_SERVER['REQUEST_METHOD'] == 'POST'
    ) {
        $columnId = 120;
        $url = "https://xxxxxxxxxx{$columnId}_Brand.js";
        $js_string = @file_get_contents($url);
        // 請求品牌失敗
        if ($js_string === false) {
            echo json_encode(array('code' => '10001', 'msg' => '請求品牌失敗'));
            die;
        }
        // 去除 "var Brand = eval(" 與 ")"
        $array_data = explode('(', $js_string);
        $string = rtrim($array_data[1], ')');

        // 獲取js定時腳本時間
        $filename = 'fashionTopBrands.txt';
        $data_put = @file_put_contents($filename, $string);
        if (!$data_put) {
            echo json_encode(array('code' => '10001', 'msg' => '請求品牌失敗'));
            die;
        }
        $update_file_time = $this->topBrandsModel->getFileModifyTime($filename);

        if (file_exists($filename)) {
            $fp = @fopen($filename, "r");
            // 指定讀取大小,這裏把整個文件內容讀取出來
            $str = fread($fp, filesize($filename));
        } else {
            echo json_encode(array('code' => '10001', 'msg' => '請求品牌失敗'));
            die;
        }

        $data = json_decode($str, true);
        echo json_encode(
            array(
                'code' => '0',
                'msg' => '請求品牌成功',
                'data' => $data,
                'info' => array('time' => $update_file_time),
            ));
        die;
    } else {
        echo 'Access forbidden!';
        exit;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章