While using a certain API to extract information the docs suggest that I need to pass a URL to retrieve data. The data is returned in XML, however to receive it in JSON format HTTP Accept header value of 'application/json' should be specified.
I am trying to achieve this in PHP, e.g. the URL to retrieve information is http://www.example.com?someContent which returns data in XML.
I am currently using http_get function from PHP, however, it doesn't seem to be working at all.
Any suggestions on how can I extract information and then also request it in JSON format.
The above link is invalid. This documentation exists at http_get
Untested, but this should work. Set the headers option to an array of headers you want to use.
$response = http_get("http://www.example.com/?someContent", array(
'headers' => array(
'Accept' => 'application/json'
)
), $info);
print_r($info);
http://php.net/manual/en/function.http-get.php
Try: $body = http_parse_message(http_get($url))->body; then you can use $body.
Alternatively, you can use cURL. Since the result is in JSON, you'll need to parse the XML then output as an array into the json_encode function.
Related
One of my partners has an API service which should send an HTTP POST request whenever a new file is published. This requires me to have an api file which will get the POST this way:
http://myip:port/api/ReciveFile
and requesting that the JSON format request should be:
{
"FILE ":"filename.zip",
"FILE_ID":"123",
"FILE_DESC":"PRUPOUS_FILE",
"EXTRAVAR":"",
"EXTRAVAR2":"",
"USERID":" xxxxxxxxxxxx",
"PASSWORD":"yyyyyyyyyyy"
}
Meanwhile it should issue a response, in JSON format if it got the file or not
{"RESULT_CODE":0,"RESULT_DESCR":""}
{"RESULT_CODE":1001,"RESULT_DESCR":"Bad request"}
And after, when I am finished elaborating the file, I should send back the modified file same way.
The question is, now basically from what I understand he will send me the variables witch I have to read, download the file, and send a response back.
I am not really sure how to do this any sample code would be welcomed!
I'm not sure exactly what the question is, but if you mean creating a success response in JSON for if an action occurred while adding data to it which is what can be understood from the question, just create an array with the values you wish to send back to the provider and do json_encode on the array which should create json and just print it back as a response.
About receiving the information; all you have to do is use the integrated curl functions or use a wrapper (Guzzle, etc) to output the raw JSON or json_decode data into a variable and do whatever you please with it.
From what I read in the question, you wish to modify the contents of it. This can be achieved by just decoding the json and changing the variables in the array, then printing the modified JSON back as a response.
Example (this uses GuzzleHTTP as an example):
$res = $client->request('GET', 'url');
$json = $res->getBody();
$array = json_decode($json, 1); // decode the json
// Start modifying the values or adding
$array['value_to_modify'] = $whatever;
$filename = $array['filename']; // get filename
// make a new request
$res = $client->request('GET', 'url/'.$filename);
// get the body of specified filename
$body = $res->getBody();
// Return the array.
echo json_encode($body);
References:
http://docs.guzzlephp.org/en/latest/
I use Unirest for PHP to do some HTTP Requests. Everything works fine, until I want to pass a fairly complex JSON to my Node.js router.
First I do a GET request that returns a JSON Object, then I extend this JSON object (needs to be done, I know it sucks) and want to feed it back into my other http POST request... and here is where the trouble starts:
I echoed the JSON that is returned and copied the output into postman -> works fine. If I want use the JSON directly in PHP in next request:
$teamsMemberOf is the variable which is containing the GET response.
$headers = array("Accept" => "application/json");
$newBody = '{"team":'.$teamsMemberOf->raw_body.'}';
$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/my/route/".$result['_id']."/get-something-from-server", $headers, $newBody);
and it doesn't work.
Error is 500 and 'Cannot read property '0' of undefined' which is certainly related to something in the JSON object.
Does someone have an idea how to fix it?
I have been given a URL that I need PHP to post data to, anonymously, without the end user knowing about it.
The exact structure is:
https://example.com/api/rest/example/createSubscription?email=1#1.com&subscriberNumber=12345JD&subscriberGroup=shop&firstName=Joe&lastName=Bloggs&offerCode=ex1&licenseParameters="STARTDATE%3D2014-08-11%26ENDDATE%3D2014-09-11"
Obviously this is a dynamic URL and I have set it up to be. I am not sure about the best way to approach this issue. Would it be a PUT http_request? I have tried that using the following but it returns a 400 error.
$url = 'https://example.com/api/rest/example/createSubscription?email=1#1.com&subscriberNumber=12345JD&subscriberGroup=shop&firstName=Joe&lastName=Bloggs&offerCode=ex1&licenseParameters="STARTDATE%3D2014-08-11%26ENDDATE%3D2014-09-11"';
$options = array(
'method' => 'PUT',
'timeout' => 15,
'header' => "Content-type: html/txt",
);
$response = http_request($url, $options);
As for your last comment, if the subscription is created simply opening the url in the browser then it is a GET request.
You can perform a GET request using file_get_contents
It's really strange you use PUT method with GET paramater.
After checking php manual here you don't use correctly this methode. that's why the server can't understand your request.
you can look after this function to do a PUT request
Send request to api website and then api give me some data in array format, how to work with this data ?
When I access to: example.com/api.php?name=papaya, it's will show
Array ( [0] => papaya [1] => fruit )
in my site, I want to work with this array data like
$url = "example.com/api.php?name=papaya ";
if ($url[1] == "fruit" )
{ echo "food"; }
How to do that?
You guys aren't understanding what the OP is asking. He's asking how he can use the data that is returned from the api request. I don't think he has access to the API itself but rather the end-point.
Now to answer the question.
Basically you'd need to either use cURL or something like file_get_contents().
For this example, I'm going to use file_get_contents() to give you a basic idea:
Now the below example will get the returned data from the geoplugin.net api.
$ip = $_SERVER['REMOTE_ADDR'];
$result = #json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
print_r($result);
?>
For your case, you'd do something similar:
<?php
$result = #json_decode(file_get_contents("example.com/api.php?name=papaya"));
// do what you need to with result...
echo $result[0];
?>
Obviously this isn't the best way to do it; as you'd need to make sure there were no errors (suppressed the errors with the # before the json_decode()).
Now I'm not going spoon feed you, so here are some examples on how to do some cURL requests.
PHP.NET cURL Examples
Simple PHP cURL Example
All examples of PHP cURL....
If you have control over the API, then set the response header Content-Type: application/json, then json_encode any output, and json_decode on the client side.
Otherwise theres not much you can do with that string.. possibly use a regex method to extract the key and values?
I'm using PHP to connect to an API and register some info using JSON and HTTP POST but it is not going well.
That is what I do:
I create a JSON object with the json_encode function:
$name = 'Mike';
$surname = 'Hans';
$fields = array('name' => json_encode($name), 'surname' => json_encode($surname));
$postData = json_encode($flds);
Once i have the post data, I just connect to the API with curl and login with oauth, but the API responde says:
JSON text must be an object or array (but found number, string, true,
false or null, use allow_nonref to allow this)
I have checked the allow_nonref in Google, but i could not find anything for PHP, all I have found is for Perl. Does anyone have any solution/advice to solve this?
Thanks!
You probably need to send the entire POST as JSON without nesting calls to json_encode, like this:
$fields = array('name' => $name, 'surname' => $surname);
$postData = json_encode( $fields);
To follow up on #nickb's answer, please only use one call to json_encode, it's far better at constructing valid json that you and I are, and it's more efficient to boot! (though we are entering the realm of micro-optimisation).
Have you tried taking the output of the json_encode and putting it into a validator/formatter such as the one here : http://jsonviewer.stack.hu/
Also, I think another likely problem could be the headers you are sending? The recieiving server could be strict and enforce that you use the correct 'Content-Type'. Are there any API docs avaliable?