問題描述
來自 URL 的 file_get_contents 僅適用於本地服務器 (file_get_contents from URL works on local server only)
我剛剛開始學習 PHP,並開始編寫從 Myfxbook 頁面提取公共數據的代碼。是否有任何可能的答案為什麼以下函數在我的本地 XAMPP 服務器上運行良好並返回我需要的值但在將其上傳到我的共享託管服務器後它返回 0?
function loadFromURL($url) {
$html = file_get_contents($url);
$doc = new DOMDocument();
$doc‑>loadHTML($html);
$stats = $doc‑>getElementById("stats");
$firstLi = $stats‑>childNodes[1];
$secondSpan = $firstLi‑>childNodes[1];
$strVal = $secondSpan‑>textContent;
$roundGainPC = floatval($strVal);
return round($roundGainPC);
}
什麼更奇怪我的代碼中的第二個函數也適用於我的本地服務器和共享 Web 服務器:
function loadFromURL2($url) {
$html = file_get_contents($url);
$doc = new DOMDocument();
$doc‑>loadHTML($html);
$stats = $doc‑>getElementById("historyTotalSpan");
$strVal = $stats‑>textContent;
$totalTrades = preg_replace('/[^0‑9]/', '', $strVal);
return round($totalTrades);
}
對於這個測試項目,我將公共系統之一用於這兩個函數:https://www.myfxbook.com/members/autotrade/turtle‑eur/1644166</一個>
理想情況下,第一個函數將返回當前為 174(四捨五入)的總增益。相反,它在實時服務器上返回 0。
參考解法
方法 1:
I think the function file_get_contents
is sweet to get file from local drive Use curl instead.
function loadFromURL($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$html = curl_exec($ch);
$doc = new DOMDocument();
$doc‑>loadHTML($html);
...
curl_close($ch);
}