file_get_contents() returns an empty string when authenticating, otherwise fine

我怕爱的太早我们不能终老 提交于 2019-12-25 15:55:53

问题


So, I'm new to working with API's and PHP, so bear with me. I'm trying to hit an API to authenticate into the site via GET parameters (as suggested in the API documentation). I'm trying to use file_get_contents() to return the authentication token it returns. A redirect to the URL outputs the token in XML format.

However, when I do the following, it returns an empty string. How can I return the full XML output?

$token = file_get_contents('http://example.com/api.asp?cmd=logon&email=xxx@something.com&password=s0mep@SSword');
var_dump($token);

I get the following output:

string(116) ""

Any ideas about what I'm doing wrong?


回答1:


Try doing:

$token = str_replace("<", "&lt;", $token);
$token = str_replace(">", "&gt;", $token);

vd($token);

This is occurring because your browser is interpreting the XML you're reading as HTML and reading the XML as tags. (You can tell the string is not empty because vd, which I'm assuming is an alias for var_dump tells you the string's length is 116.) Replacing the <'s and >'s with their valid HTML entities should resolve that.




回答2:


Assumning the API is returning XML, you can use SimpleXML in PHP to directly parse the file:

 <?php
 $token = simplexml_load_file('http://example.com/api.asp?cmd=logon&email=xxx@something.com&password=s0mep@SSword');
 vd($token);
 ?>


来源:https://stackoverflow.com/questions/5954840/file-get-contents-returns-an-empty-string-when-authenticating-otherwise-fine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!