小编Jam*_*mes的帖子

有没有更好的方法循环这些 PHP 代码,也许使用 foreach 循环?

file_get_contents用来获取远程定价(每天更新),用于substr仅保留我想要的部分(从输出中去除货币符号和其他数据并仅保留数字)并用于file_put_contents将其存储到我引用的缓存目录中到以后。

这就是我现在所拥有的:-

<?php

$cacheDirectory = $_SERVER['DOCUMENT_ROOT'] . '/cache/';

// Small Plan - US
$cachefile_SM_US = $cacheDirectory . 'SM_US.cache';

if(file_exists($cachefile_SM_US)) {
    if(time() - filemtime($cachefile_SM_US) > 1600) {
        // too old , re-fetch
        $cache_SM_US = file_get_contents('https://remotedomain.com/?get=price&product=10&currency=1');
        $substr_SM_US = substr($cache_SM_US,17,2);
        file_put_contents($cachefile_SM_US, $substr_SM_US);
        } else {
            // cache is still fresh
    }
} else {
    // no cache, create one
    $cache_SM_US = file_get_contents('https://remotedomain.com/?get=price&product=10&currency=1');
    $substr_SM_US = substr($cache_SM_US,17,2);
    file_put_contents($cachefile_SM_US, $substr_SM_US);
}

// Large Plan - US
$cachefile_LG_US = $cacheDirectory . …
Run Code Online (Sandbox Code Playgroud)

php foreach loops file-get-contents file-put-contents

3
推荐指数
1
解决办法
77
查看次数