我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¤cy=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¤cy=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 . 'LG_US.cache';
if(file_exists($cachefile_LG_US)) {
if(time() - filemtime($cachefile_LG_US) > 1600) {
// too old , re-fetch
$cache_LG_US = file_get_contents('https://remotedomain.com/?get=price&product=20¤cy=1');
$substr_LG_US = substr($cache_LG_US,17,2);
file_put_contents($cachefile_LG_US, $substr_LG_US);
} else {
// cache is still fresh
}
} else {
// no cache, create one
$cache_LG_US = file_get_contents('https://remotedomain.com/?get=price&product=20¤cy=1');
$substr_LG_US = substr($cache_LG_US,17,2);
file_put_contents($cachefile_LG_US, $substr_LG_US);
}
当只有两种产品 (10和20) 和两种货币 (1和2) 时,这种手动方式有效,因为我只需要这样做 4 次就可以获得我需要的所有定价。
但是,我打算将产品数量显着扩大到至少 12 种产品和 9 种货币,因此手动完成它们是不现实的。
我相信这可以通过 PHP foreach 循环更有效地完成,但我尝试了几天但没能成功,这可能是因为我对这个概念的理解较弱。
心有法竹
Smart猫小萌
ITMISS
随时随地看视频慕课网APP