Convert html to json in php laravel - php

Im hitting this url
https://graph.facebook.com/1843624489016097?fields=link&access_token=EAAD3ZBKkIhYMBAL3KRi9eZBXlYJADZARRFMSe0Nc35WTP92X2etkccVqnjNcjJgKbd8ABtX5pyDPN0nAA7jORyjpOGexZCYp1Sf2iw0DJjCf8UkPiLwhuApSGDGZBvy5w7vk3U0Ba97FZA2DO7J4m4UjvbIolDaRP9TRpemEmLyQZDZD
with the below code in php,
$url ='https://graph.facebook.com/' . $connection->provider_id . '?fields=link&access_token=' . $connection->token;
$ch = curl_init($url);
$json= curl_exec ($ch);
I have this html coming from Facebook, I want to use only "Link" in this,
{"link":"https:\/\/www.facebook.com\/app_scoped_user_id\/YXNpZADpBWEdrUlJiUzc0SWFWZATI4SEVJUmJHTTJQVHU2M3owcTJLOHh5MnJYOTI0LWdMT3VFUC1veXNWdXBhM3o3RzdkQmV4cjNfTC1nSkdheGFhV19pWWU5T1ZAWSzlkN0NBTUl4NVZAKTE9oRjlFbjdObU5i\/","id":"1686741234967769"}1
I tried converting that into JSON but its not working, Its coming in same format, since im doing this in a API, im checking this under Postman, I did like this..
$request = json_encode($json, JSON_HEX_QUOT | JSON_HEX_TAG);
The format is not getting convert to json, Im doing in PHP Laravel.

There's a 1 at the end of the output, possibly you're echoing something extra that you shouldn't .
I suspect you expect curl to return the actual result but you are not using the appropriate flag. The reason I suspect that is because you are assigning the return result to $json but without the flag CURLOPT_RETURNTRANSFERwill return true and not any json value.
Here's what you can try:
$url ='https://graph.facebook.com/' . $connection->provider_id . '?fields=link&access_token=' . $connection->token;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER);
$json= curl_exec ($ch);
$jsonArray = json_decode($json, true);
$link = $jsonArray["link"];
More information on the curl flags in the manual

You should use json_decode in place of json_encode. So you should try like:
$request = json_decode($json, true);
$link = $request["link"];
Also use curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); to save response in variable just after curl_init.

Related

return Json string not working

I want to get data from api..
but I have trouble with json ..I can not get json string .. it print as normal string or xml..
I try multi method from net but no solution..
this my code:
$url = "http://fv4online.com/egov_api/v1/students/7";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Accept:
application/json;charset=UTF-8'));
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
print_r($output);
$t=json_decode($output,true);
print_r($t);
// close curl resource to free up system resources
curl_close($ch);
result of print ($output) is string:
7345345343testtesttesttest2000testliterary4564620171testDamascusar_lang300600350en_lang160400200fr_lang160400200national80200100history120300200geograph120300200philosophy160400300religion802001501700155060successful
and result of print(var_dump($output)) is xml:
'
7345345343testtesttesttest2000testliterary4564620171testDamascusar_lang<'... (length=1544)
note: Previously I was able to get this data without any problems, but suddenly the problem arose
That string contains all values the XML from the url returns, just without the tags around them. If you do 'View Source' you'll see more.
You get XML, not JSON. Could be they've changed that (which would be a bit odd, but I've seen worse). If you want is as JSON:
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);

JSON text unparseable when using cURL to grab it?

I have this really long JSON string: http://pastebin.com/2jJKSGHs , which is being pulled from a music API.
I have this code set up to parse it ( http://pastebin.com/EuJtuhHg ):
$url = "https://api.discogs.com/database/search?type=artist&q=pink[keyandsecretredacted]";
//initialize the session
$ch = curl_init();
//Set the User-Agent Identifier
curl_setopt($ch, CURLOPT_USERAGENT, 'YourSite/0.1 +http://your-site-here.com');
//Set the URL of the page or file to download.
curl_setopt($ch, CURLOPT_URL, $url);
//Ask cURL to return the contents in a variable instead of simply echoing them
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Execute the curl session
$output = curl_exec($ch);
//close the session
curl_close ($ch);
//decode and print output
$output = json_decode($output2, true);
echo($output['results'][0]['title']);
When I insert the contents of the JSON string directly into my code, the json_decode works perfectly on it. But when I try to grab it from the API using the method above, nothing prints on my page -- it's just empty. Printing out json_last_error returns "0", so it's not detecting any errors.
Any ideas why this might be happening?
Replace
$output = curl_exec($ch);
with
$output2 = curl_exec($ch);
Otherwise $output2 isn't defined, and json_decode is using an undefined variable:
$output = json_decode($output2, true);

PHP string specialchars

I'm setting up a little webservice usable via an app on Android.
The function in the server is this:
$lat=43.0552592;
$lng=12.4483577;
$radius=2000;
$url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=italian&location=".$lat.",".$lng."&radius=".$raidus."&types=restaurant&sensor=false&key=".$apiKey;
$urlW = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=italian&location=43.0552592,12.4483577&radius=2000&types=restaurant&sensor=false&key=XXXXxxxXXxxXXxxxxXXX";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Get the response and close the channel.
$response = curl_exec($ch);
return $response;
The trouble is that if I query Google with the $url (as in the above example) it returns the JSON with 'INVALID REQUEST', but if the query at the first curl_opt is done with $curlW will works like a charm.
While debugging that I've discovered, making $url return, that gets every & converted (before the curl_init!) in &amp...!
So I've tried almost every PHP string function to force every & decode or replacing every &entities to & only without any result.
Any suggestion?
you've done something wrong,
$url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=italian&location=".$lat.",".$lng."&radius=".$raidus."&types=restaurant&sensor=false&key=".$apiKey
should be
$url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=italian&location=".$lat.",".$lng."&radius=".$radius."&types=restaurant&sensor=false&key=".$apiKey;
but i don't guess that is what is doing the problem, try using file_get_contents() instead of curl, so $response will be like this:
$response = file_get_contents($url);

PHP curl() Response to Associative Array

I have recently started working with the PHP curl() function and I am trying to convert my retrieved JSON object to an associated array. Can anybody point me in the right direction? Thanks!
<?php
$ch = curl_init("https://canvas.instructure.com/api/v1/courses?access_token=7~8SXvaXHjMFZFHAdU5yU0pxNmVwAj40sjW7jRHw1Bvzq09QTFWrJRFxTu4pHAqSZU");
curl_exec($ch);
curl_close($ch);
?>
The response:
[{"account_id":81259,"course_code":"CS50","default_view":"feed","id":870674,"name":"CS50","start_at":"2014-08-05T18:29:18Z","end_at":null,"public_syllabus":false,"storage_quota_mb":250,"apply_assignment_group_weights":false,"calendar":{"ics":"https://canvas.instructure.com/feeds/calendars/course_6QRRvAKDngrrXtTBhzCA5Oz46g3aLgfRt7PNH0NN.ics"},"enrollments":[{"type":"student","role":"StudentEnrollment","enrollment_state":"active"}],"hide_final_grades":false,"workflow_state":"available"}]
Use CURLOPT_RETURNTRANSFER to capture the result in a string, which is what you pass to json_encode. I think you're passing $ch to json_decode which is not what you want. (As the error message states, $ch is a resource and json_decode expects to be passed a string).
$ch = curl_init("https://canvas.instructure.com/api/v1/courses?access_token=7~8SXvaXHjMFZFHAdU5yU0pxNmVwAj40sjW7jRHw1Bvzq09QTFWrJRFxTu4pHAqSZU");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// ...
$response = curl_exec($ch);
// $response will be false if the curl call failed
if($response) {
var_dump(json_decode($response, true));
}
See curl_setopt documentation for more information.

Http post request with JSON String in PHP

Here is my code,
$url= 'http://dummyhost:8080/admin/EditSubscriber?jsonString={"sub_Id":3,"sub_Fname":"messi","sub_Lname":"lionel"}';
$data_string="";
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($data_string);
$request->send();
$response = $request->getResponseBody();
$response= json_decode($response, true);
at the end of url JSON string is concatenated according to server requirement
but in response there is nothing i get in response variable.
What is wrong with this as when i make this request using chrome extension it shows me the result updated. And when i use the $url= "http://dummyhost:8080/admin/ViewSubsriber?jsonString={"sub_Name":"messi","sub_Password":"password"}";
i get the desired result.
i've used curl as well'
i've used Curl as well like this
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
curl_close($ch);
$json_result = json_decode($result, true);
but the same result i get that is nothing
If you have created JSON string at your own keep following things in mind:
Space in string might result in unnatural behavior from server so for each of the varible or atleast for strings use
urlecode(yourvariable);
then chek the string online wether the JSON string is valid or not like this
http://json.parser.online.fr/
Like Brant says use
$json = file_get_contents('php:://input');
for raw data instead of using the empty $data_string="";
Your posted variable, $data_string, is empty. You are using POST and sending empty data, but then also sending a query string. It seems you are mixing GET and POST methods here. You need to actually post your JSON string in the posted data.
If you are posting raw JSON string using application/JSON content type, the post data will need to be read from raw input like this
$json = file_get_contents('php:://input');
This is because $_POST is only automatically populated by PHP for form-encoded content types.
I would also recommend sticking with curl for such usage.

Categories