file_get_contents() returns an empty string when authenticating, otherwise fine
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开发者_JAVA技巧://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?
Try doing:
$token = str_replace("<", "<", $token);
$token = str_replace(">", ">", $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.
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);
?>
精彩评论