來自 URL 的 file_get_contents 僅適用於本地服務器 (file_get_contents from URL works on local server only)


問題描述

來自 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);
    }

(by MarkPascal Tovohery)

參考文件

  1. file_get_contents from URL works on local server only (CC BY‑SA 2.5/3.0/4.0)

#domdocument #DOM #PHP






相關問題

PHP/DOMDocument: unset() 不釋放資源 (PHP/DOMDocument: unset() does not release resources)

C++ Xerces Parser 加載 HTML 並蒐索 HTML 元素 (C++ Xerces Parser Load HTML and Search for HTML Elements)

Cách lấy tên thuộc tính kiểu bằng PHP xpath (How to get the style property name using PHP xpath)

DOMDocument:如何解析類似 bbcode 的標籤? (DOMDocument : how to parse a bbcode like tag?)

如何使用 DOMDocument 獲取此 html 中的 url (How to use DOMDocument to get url in this html)

DomDocument 未能為 RSS 提要添加“鏈接”元素 (DomDocument failing to add a "link" element for RSS feed)

如何防止將文檔類型添加到 HTML 中? (How to prevent the doctype from being added to the HTML?)

PHP DOM 文檔回顯問題 (PHP DOMdocument echoing problem)

使用 PHP 將數據放到服務器上(新的 DOMdocument 不起作用) (Use PHP to put data onto server ( new DOMdocument not working))

有沒有辦法構建類似於 DOMDocument 構建 HTML 文檔的 SQL 查詢? (Is there a way to build SQL queries similar to how DOMDocument builds HTML document?)

來自 URL 的 file_get_contents 僅適用於本地服務器 (file_get_contents from URL works on local server only)

使用多個 <table> 標記抓取 HTML 頁面並從特定的 <a> 標記後代中提取文本 (Scrape HTML page with multiple <table> tags and extract text from specific <a> tag descendants)







留言討論