Parsing JSON request with php (JSON in specific format) [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 7 years ago.
I am trying to get the indications_and_usage part in the results section from the following JSON URL: https://api.fda.gov/drug/label.json?search=levodopa
Till now, I have
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$data = curl_exec($ch);
curl_close($ch);
in my php file. When I echo $data, it gives the entire json as output. How can I modify this to get the indications_and_usage part?
As none of the methods seem to be working, here is the beginning output when I do
echo $data;
HTTP/1.1 200 Connection established HTTP/1.1 200 OK Access-Control-Allow-Headers: X-Requested-With Access-Control-Allow-Origin: * Age: 0 Cache-Control: public, max-age=60 Content-Security-Policy: default-src 'none' Content-Type: application/json; charset=utf-8 Date: Sun, 21 Feb 2016 19:49:27 GMT ETag: W/"19923-bQuoDHROKCsX/qDsyE4GuA" Server: openresty Vary: Accept-Encoding Vary: Accept-Encoding Vary: Accept-Encoding Via: http/1.1 api-umbrella (ApacheTrafficServer [cSsSfU]) X-Cache: MISS X-Content-Type-Options: nosniff X-Frame-Options: deny X-XSS-Protection: 1; mode=block Content-Length: 104739 Connection: keep-alive { "meta": { "disclaimer": "openFDA is a beta research project and not for clinical use. While we make every effort to ensure that data is accurate, you should assume all results are unvalidated.", "license": "http://open.fda.gov/license", "last_updated": "2016-02-05", "results": { "skip": 0, "limit": 1, "total": 1400 } }, "results": [ { "effective_time": "20120305", "drug_interactions": [ "DRUG INTERACTIONS Few systemic data have been collected on the metabolism of bupropion following concomitant administration with other drugs or, alternatively, the effect of concomitant administration of bupropion on the metabolism of other drugs. ..... and so on

You have to remove curl_setopt($ch, CURLOPT_HEADER, 1); form your curl. Otherwise the http header is included in the variable $data.
Full Example Code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$result = json_decode($data, true);
$result_string = $result['results'][0]['indications_and_usage'][0];
echo $result_string;

$json = file_get_contents("https://api.fda.gov/drug/label.json?search=levodopa");
$obj = json_decode($json);
echo "<pre>";
print_r($obj->results[0]->indications_and_usage);
echo "</pre>";
If you do print_r or var_dump on the whole object, you'll see that results is one of its members, an array. The first index of the results array is another object, which has an indications_and_usage member, the one you want.

You should be able to access it with:
$decoded = json_decode($data, true);
echo $decoded->results[0]->indications_and_usage[0]

Related

PHP - curl post view request body (parameters)

I get an error response for missing parameter when posting cURL POST method,
I'm adding an array of parameters to CURLOPT_POSTFIELDS the following way:
$service = "AutoInsuranceFormPostService";
$method = "autoInsurancePublisherFormPost";
$userAgent = "Mozilla%2F5.0+%28Linux%3B+Android+4.4.4%3B+Z752C+Build%2FKTU84P%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F36.0.1985.135+Mobile+Safari%2F537.36";
$payload = $encodedPayLoad;
$parameters = array (
'service' => $service,
'method' => $method,
'UserAgent' => $userAgent,
'payload' => $payload
);
With:
curl_setopt($ch,CURLOPT_POSTFIELDS,$parameters);
Since the response is saying missing parameter "service", I figured I need to debug the request body.
I managed to get the headers with:
curl_getinfo($ch)
I also attempted to use:
curl_setopt($ch, CURLOPT_VERBOSE, true);
But unfortunately in both cases I only got the headers and not the body (the parameters values).
Full curl execution function:
function openurl($url, $postvars) {
$ch=curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$result = curl_exec($ch);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
return $result;
}
Verbos information:
Content-Length: 6659
Expect: 100-continue
Content-Type: application/x-www-form-urlencoded; boundary=------------------------45b2d9f6776306b0
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Date: Thu, 12 Jul 2018 16:32:52 GMT
< Server: Apache
< Cache-Control: public
< ORIGIN: S_CACHE
< Vary: User-Agent,Accept-Encoding
< Set-Cookie: _qs_origin=s-cache; path=/;
< Set-Cookie: _qs_deviceType=; path=/;
< Content-Length: 141
< Content-Type: application/json;charset=ISO-8859-1
<
This output is useless for me since I cannot see how the parameters were sent and those cannot fix their format.
The response I get is:
{"Status":"Fail","StatusCode":"400","ResponseMessage":"\"service\" parameter empty! || \"method\" parameter empty! ","SkipMatchingFlag":"No"}
I have been searching for a solution all day long, I've seen a ton of answers on "How to see the RESPONSE body", and "How to see the request HEADERS".
But none for "How to see the request body", so any help would be much appreciated,
Best regards.

Subscribe using Superfeedr PubSubHubbub generating error hub.topic not found

I want to integrate Superfeedr API using PubSubHubbub in PHP. I am following this and my code is:
<?php
require_once('Superfeedr.class.php')
$superfeedr = new Superfeedr('http://push-pub.appspot.com/feed',
'http://mycallback.tld/push?feed=http%3A%2F%2Fpush-pub.appspot.com%2Ffeed',
'http://wallabee.superfeedr.com');
$superfeedr->verbose = true;
$superfeedr->subscribe();
?>
And my subscribe() function is
public function subscribe()
{
$this->request('subscribe');
}
private function request($mode)
{
$data = array();
$data['topic'] = $this->topic;
$data['callback'] = $this->callback;
$post_data = array (
"hub.mode" => 'subscribe',
"hub.verify" => "sync",
"hub.callback" => urlencode($this->callback),
"hub.topic" => urlencode($this->topic),
"hub.verify_token" => "26550615cbbed86df28847cec06d3769",
);
//echo "<pre>"; print_r($post_data); exit;
// url-ify the data for the POST
foreach ($post_data as $key=>$value) {
$post_data_string .= $key.'='. $value.'&';
}
rtrim($fields_string,'&');
// curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->hub);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_USERPWD, 'USERNAME:PASSWORD');
$output = curl_exec($ch);
if ($this->verbose) {
print('<pre>');
print_r($output);
print('</pre>');
}
}
But after execution I am getting this error
HTTP/1.1 422 Unprocessable Entity
X-Powered-By: The force, Luke
Vary: X-HTTP-Method-Override, Accept-Encoding
Content-Type: text/plain; charset=utf-8
X-Superfeedr-Host: supernoder16.superfeedr.com
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
Content-Length: 97
ETag: W/"61-db6269b5"
Date: Wed, 24 Aug 2016 14:01:47 GMT
Connection: close
Please provide a valid hub.topic (feed) URL that is accepted on this hub. The hub does not match.
Same data (topic and callback etc..) requesting from https://superfeedr.com/users/testdata/push_console
is working fine. But I don't know why I am getting this error on my local. If anyone has any experienced with same problom then please help me. Thanks.
You are using a strange hub URL. You should use HTTPS://push.superfeedr.com in the last param of your class constructor.

How to perform a PUT operation using CURL in PHP?

I would like to perform a PUT operation on a webservice using CURL. Let's assume that:
webservice url: http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3
municipality= NMBM
sgc= 12345
I've written the code below, but it outputs this error message: "ExceptionMessage":"Object reference not set to an instance of an object.". Any help would be so much appreciated. Thanks!
<?php
function sendJSONRequest($url, $data)
{
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'X-MP-Version: 10072013')
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();
$result = curl_exec($ch);
$info = curl_getinfo($ch);
if ($result === false || $info['http_code'] == 400) {
return $result;
} else {
return $result;
}
ob_end_clean();
curl_close($ch);
}
$mun = $_GET['municipality'];
$sgc = $_GET['sgc'];
$req = $_GET['req']; //cac52674-1711-e311-b4a8-00155d4905d3
//myPrepaid PUT URL
echo $mpurl = "http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/$req";
// Set Variables
$data = array("Municipality" => "$mun", "SGC" => "$sgc");
//Get Response
echo $response = sendJSONRequest($mpurl, $data);
?>
I copied your code, but changed it so it pointed at a very basic HTTP server on my localhost. Your code is working correctly, and making the following request:
PUT /api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3 HTTP/1.1
Host: localhost:9420
Content-Type: application/json
Accept: application/json
X-MP-Version: 10072013
Content-Length: 37
{"Municipality":"NMBM","SGC":"12345"}
The error message you're receiving is coming from the stageapi.myprepaid.co.za server. This is the full response when I point it back to them:
HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 30 Aug 2013 04:30:41 GMT
Connection: close
Content-Length: 867
{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at MyPrepaidApi.Controllers.ConsumerRegisterRequestController.Put(CrmRegisterRequest value) in c:\\Workspace\\MyPrepaid\\Prepaid Vending System\\PrepaidCloud\\WebApi\\Controllers\\ConsumerRegisterRequestController.cs:line 190\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
You may want to check out the API to make sure you're passing them the correct information. If you are, the problem could be on their end.
And while I realize this isn't part of your question and this is in development, please remember to sanitize any data from $_GET. :)
Try with:
curl_setopt($ch, CURLOPT_PUT, true);

regex to extract this string or use json decode

In PHP what would the regex be to extract "taken" from below, considering that it is dynamic and is always after status:
HTTP/1.0 200 OK
Date: Sat, 09 Feb 2013 23:07:09 GMT
Accept-Ranges: bytes
Server: Noelios-Restlet-Engine/1.1.7
Content-Type: application/json;charset=UTF-8
Content-Length: 147
X-Cache: MISS from geonisis-2.eurodns.com
X-Cache-Lookup: MISS from geonisis-2.eurodns.com:80
Via: 1.0 geonisis-2.eurodns.com (squid/3.1.10)
Connection: keep-alive
{"service":"availability","domain":"","timestamp":1360451229,"content":{"domainList":[{"status":"taken","name":""}]}}
The following shows that I should be using json decoded. How would one achieve this?
The above in generated using:
$process = curl_init($host);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
Remove the header from the response by changing:
curl_setopt($process, CURLOPT_HEADER, false);
And then decode the JSON string with:
$data = json_decode($curlResponse, true);
If you discard headers from the response, you can use:
$json = '{"service":"availability","domain":"","timestamp":1360451229,
"content":{"domainList":[{"status":"taken","name":""}]}}';
$data = json_decode($json, TRUE);
echo $data['content']['domainList'][0]['status'];
Why care about the header? That's a JSON string, just decode it and you'll have an object that you can access easily
in php:
$jsonobj = json_decode('{"service":"availability","domain":"","timestamp":1360451229, "content":{"domainList":[{"status":"taken","name":""}]}}');
in javascript:
var jsonobj = JSON.parse('{"service":"availability","domain":"","timestamp":1360451229,"content":{"domainList":[{"status":"taken","name":""}]}}');
$string = '
HTTP/1.0 200 OK
Date: Sat, 09 Feb 2013 23:07:09 GMT
Accept-Ranges: bytes
Server: Noelios-Restlet-Engine/1.1.7
Content-Type: application/json;charset=UTF-8
Content-Length: 147
X-Cache: MISS from geonisis-2.eurodns.com
X-Cache-Lookup: MISS from geonisis-2.eurodns.com:80
Via: 1.0 geonisis-2.eurodns.com (squid/3.1.10)
Connection: keep-alive
{"service":"availability","domain":"","timestamp":1360451229,"content":{"domainList":[{"status":"taken","name":""}]}}';
$parts = explode("\n", $string);
$json = end($parts);
$data = json_decode($json);
$status = $data->content->domainList[0]->status; die;
echo $status;
Edit (based on the question update):
Remove the CURLOPT_HEADER line from your cURL request. This would simplify the response and make it easier to parse.
If you need to work with headers, you have two options;
// first: regex
preg_match('~"status":"(.*?)"~i', $return, $match);
// print_r($match);
echo $match[1]; // taken
// second: json encode
$response = explode("\r\n\r\n", $return, 3);
// print_r($response);
$json_object = json_decode($response[2]);
$json_array = json_decode($response[2], true); // toArray
// echo $json_object->content->domainList[0]->status;
echo $json_array['content']['domainList'][0]['status'];

how to handle box.net download responce in php

i am trying to download a file using box.net using API in php.
As per the documentation i wrote up the code.
but in response i am getting some strange texts.
here's my code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.box.com/2.0/files/3934139624/content ");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPGET,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: BoxAuth api_key={MyApikey}&auth_token={Mytoken}"));
$result = curl_exec($ch);
die('DIE');
I am getting response something like this:
PK!Ðòš-[Content_Types].xml ¢( ´UËNÃ0¼#ñ‘¯¨qË!Ô´G¨Dù×Þ´‰mÙÛ×ß³IšA›ˆ†^"EÑÎÌÎÎnÆÓ]žEðA[“°QH¯~ÉŸb üv8¼ãÒƒ,0ØdüF¼VÍ„ÇW‘ßZ¯xj-‹b‚cÑcUWP'L8—i)„óQ?H6Mµeå:'ª¸€sÞJZ˳¸¾) ùdü©Xg=ïH[e‡‡,üõÐfL•¥²°Ò.´0´·uPvÒž¦»v˜3Üis¡M­ÿ¤³ÎàÉ×ÿSÝ)"à>»DP*ÜNz0êBI­‘Û$мfÞºÀi+zŠ P ´0"f3°£\…ȾTºI S‘ÌõŒ«º¾ÇôWš™¦ÚY igï#µÇX6_Ö]7~ fïØˉÈaoÙ.b*lIÆrj)õ,l0Ï%‘b¬ 6ài¢ÕõDÿ_‹Ž…, ¡ ‰Ïó|uœZ^tÙ¢yǯ;!Y,}{ûCƒ³/h>ÿÿPK!¿hJä1>word/rels/document.xml.rels ¢( ¬”ËNÃ0E÷HüCä=qR q'æ>¾ƒ“‘ˆsµà©WÃ-ŽÌEî›nâ>ðÍqã¨Í§y±3ÆóüükeìE±ty’àÕ³üÍ黦ÏÖ¤KLÏhóÊŸi¾IàˆpzÒŽ¹ç?}xÛxx;ùgïÐ¥f7Yô KéMèwÄÆÇÐEïúÃF§³ß9ètÏ7ÌKWxÐ/žñ¡“ùéâ;W…—Ô•¯bú%B×óù§ìv îã㡈“ô£ 8ÜílìÐqq~x|!Ã4Á1Nâ ñaãVš+¾•ËÓr¤ØLe'õc"ójS“Œ(ñR'»>wbriê’6œ,•ôçPøH†.ÔO«<çµ¼G›[¯ ‹Ÿ~ëÈŒcñ)“ )ò<­4/nÌ—­ôEÛþßpÄÙ÷æ¬Û?xg«\ÖîЃSäÀ•Ç°tÒ(¾‹³ƒwïg˜³ÕKøŒ;ù¾.†ì, l©´ªµÐm¯]‰ŠTíßnÁ¿·ß¤/ë»–ª”짓6õ“^Qð-wô—Qð]6bé à²#ÆûÍ#¡™˜×Fa'™Â†êMî'ÂÛ¿U*XÆÞ/¾\ÁÜl X5HñKÕ˜sØ8EÌ/!вÃÐeq”µ±dº¨É…⛂R—7ЊU¹iØF:h±FÎç¢àõð¾ôÈ!˜&æ',ADSÈP¸L‘M.úìäpow½Ý(¥Ú·R ãpK0è7^;¿Lë4f¤P­3Ì…#M s´ï¡Ü:…(#à(1ß;9|÷S½°T4ϹF²ì%“$åÁf“tÖة⼪R&˜nn†)#éóÒfŽBC?‰ð€()ÄÝ(%LNËñ)V^«ÞÛ¶[5+Í>jÀ£WlŽ÷¡¿)ÁoôFBû›CÕ©ë­Ü™ÖI¦æÖQ×ƤHX-ijž^ÀDûs“ …Ø}
Can any one tell me how can i handle such kind of response?
thanks in advance.
As per box.net api documentation:
The response to this request will simply be the complete data of the
file itself.
So all you need to save file content locally.
In response header, you need to check content-type, right now it is XML
$result = curl_exec($ch);
$fp = fopen('test.xml','wb');
fwrite($fp, $result);
fclose($fp);
#GBD following comes in response header:
HTTP/1.1 302 Found
Server: nginx
Date: Wed, 14 Nov 2012 09:11:51 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Cache-control: private
Location: https://dl.boxcloud.com/bc/1/85f471520cf611a05025a5f/JolueqOGpciD6dgYhecNBoVpYxkvmYe1ZLheZor6BF4DUBIelMQTkFwYIys3nIibNIIEHUp447tBZLaXDzIbNQ,,/a44510a2b21219463fade41d6b36dabf/
Content-Length: 0
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 14 Nov 2012 09:11:52 GMT
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Length: 19944
Connection: keep-alive
Cache-control: private
Accept-Ranges: bytes
Content-Disposition: attachment;filename="cloud computing proposal.docx";filename*=UTF-8''cloud%20computing%20proposal.docx
X-Content-Type-Options: nosniff
Accept-Ranges: bytes
And saving file in xml also,couldn't b opened.

Categories