<分区>
我正在尝试使用 file_get_html()
从 Amazon 获取页面内容,但输出在 echo
上带有奇怪的字符。谁能解释一下我该如何解决这个问题?
我还在 Stack Overflow 上发现了以下两个相关问题,但它们并没有解决我的问题。 :)
这是我的代码:
$options = array(
'http'=>array(
'header'=>
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n".
"Accept-language: en-US,en;q=0.5\r\n" .
"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6\r\n"
)
);
$context = stream_context_create($options);
$amazon_url = 'https://www.amazon.com/my-url';
$amazon_html = file_get_contents($amazon_url, false, $context);
这是我得到的输出:
��T]o�6}��`���0��݊-��"[�bh�tN�b0��.%%�$P��@�(Ų�� ������F#����A�
在浏览器窗口中会显示大约 115,000 个这样的字符。
这些是我的新标题:
$options = array(
'http'=>array(
'header'=>
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n".
"Accept-language: en-US,en;q=0.5\r\n"
)
);
使用 cURL 会解决这个问题吗?
更新:
我尝试了 cURL。仍然得到垃圾输出。这是我的响应 header :
HTTP/1.1 200 OK
Date: Sun, 18 Nov 2018 20:29:28 GMT
Server: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.5
X-Powered-By: PHP/7.2.5
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
谁能解释反对票?
- 我自己做了一项研究。
- 在 Stack Overflow 上找到了一些相关问题,但没有解决我的问题。
- 提供了我认为有帮助的所有信息。
我还应该在问题中包含什么?
这是我目前的整个 curl 代码。这是我正在抓取的 the URL。
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $amazon_url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($handle);
curl_close($handle);
echo $data;
输出只是我上面提到的一堆字符。这是我的请求 header :
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Cookie: AMCV_17EB401053DAF4840A490D4C%40AdobeOrg=-227196251%7CMCIDTS%7C17650%7CMCMID%7C67056225185486460220940124683302119708%7CMCAID%7CNONE%7CMCOPTOUT-1524907071s%7CNONE; mjx.menu=renderer%3ACommonHTML; _ga=GA1.1.2019605490.1529649408; csm-hit=adb:adblk_no&tb:s-3521C4J8F2EP1V0MMQEP|1542578145652&t:1542578146256
Upgrade-Insecure-Requests: 1
Pragma: no-cache
Cache-Control: no-cache
这些来自“网络”选项卡。响应 header 与我上面提到的相同。
这是将 curl_setopt($handle, CURLOPT_HEADER, 1);
添加到我的代码后的输出:
HTTP/1.1 200 OK Server: Server Content-Type: text/html; charset=UTF-8 Strict-Transport-Security: max-age=47474747; includeSubDomains; preload x-amz-id-1: 7A162B8JKV6MGZQ3PCH2 Vary: Accept-Encoding,User-Agent,X-Amzn-CDN-Cache Content-Encoding: gzip x-amz-rid: 7A162B8JKV6MGZQ3PCH2 Cache-Control: no-transform X-Frame-Options: SAMEORIGIN Date: Sun, 18 Nov 2018 22:42:51 GMT Transfer-Encoding: chunked Connection: keep-alive Connection: Transfer-Encoding Set-Cookie: x-wl-uid=1a4u8+XgF+IhFF/iavy9mKZCAA0g4HiIYZXR8hKjxGtmOtBW+j67wGABv7ZOTxDRcab+7Qmpjqds=;