我正在尝试使用 file_get_contents() 从页面获取 html。
以下内容效果很好: file_get_contents('http://www.mypage.com?Title=Title')
但以下内容会导致错误:
$Title = 'Title';
file_get_contents("http://www.mypage.com?Title=$Title")
错误是:
Bad Request
Your browser sent a request that this server could not understand.
The request line contained invalid characters following the protocol string.
Apache/1.3.41 Server at eiit.org Port 80
有谁知道为什么吗?
最佳答案
您正在使用带单引号的字符串;并且没有带单引号的变量插值。
这意味着您尝试获取的网址是 http://www.mypage.com?Title=$Title
,而不是 http://www.mypage.com ?标题=标题
。
您应该使用双引号字符串来进行变量插值:
$Title = 'Title';
file_get_contents("http://www.mypage.com?Title=$Title");
如果这仍然不起作用:
- 检查您的网址是否正确:不要直接将其传递给
file_get_contents
,而是将其存储在变量中并回显 - 只是为了确保其正确。 - 为什么您的网址中没有页面名称?
- 您拥有域名:
www.mypage.com
- 还有一个参数+值:
Title=Title
- 但是没有文件/页面?即,为什么没有类似
http://www.mypage.com/index.php?Title=$Title
的内容?或者甚至http://www.mypage.com/?Title=$Title
?
- 您拥有域名:
- 您可能必须urlencode您在 URL 中作为参数传递的值。
关于php - 无法使用动态创建位置的 file_get_contents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2152544/