I am using cURL to get json information from a site that pulls a random tumblr picture from a list of sources and I am interested of putting the json data retrieved into php variables so I can call for example, just the image url
$url = "http://someurl.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$a = curl_exec($ch);
$json = var_dump(json_decode($a, true));
I get:
array(3) {
'image' =>
array(1) {
[0] =>
string(62) "http://picture.jpg"
}
'source' =>
string(31) "http://source.tumblr.com"
'page' =>
string(9) "/page/164"
}
What would I now do in order to just print the url for the image?
I have tried
$url = $json["image"][0];
and then calling $url, but it gives me nothing in return. What I am doing wrong?
I have never worked with json before so I am at a loss here, any help is appreciated!
according to code looks:-
try
change
$json = var_dump(json_decode($a, true));
to
$json = json_decode($a, true);
Related
I am using curl call in php to get the response from one of the REST endpoint. The following is the code that will execute the curl call and get the result into array $result_array
$post_url = 'http://localhost:8180/auth/realms/realm-nextcloud/protocol/openid-connect/token/introspect';
$curl = curl_init($post_url);
$fields = array(
'client_id' => "test",
'client_secret' => "*****-*****",
'token_type_hint' => "access_token",
'token' => "kjfhakf"
);
//Url-ify the data to prepare for the post request
$fields_string = http_build_query($fields);
//Open the connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 4);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result_array = json_decode($result,true);
var_dump($result_array);
The var_dump of the array $result_array gives the following output:
array(1) {
["active"]=>
bool(false)
}
Although, I want to extract the value of the "active" field in the array, but I can't seem to get it with $result_array[0] or $result_array['active'].
Also, if I use var_dump($result_array["active"]) I will get the output as bool(false) but echo $result_array["active"]doesn't print anything ?
How to get the value of the field echo $result_array["active"] as false in a string?
Any help would be appreciated!
I found out that I won't be able to print out the boolean value with echo (not sure if I can print it by any other method), but the value of the field can be tested with the following code and the result can be set in the form of the string to a variable using if-else.
$result_boolean = $result_json["active"];
if($result_boolen)
{
$val = "TRUE";
echo $val;
}
else
{
$val = "FALSE";
echo $val;
}
My CURL request takes in two variables as shown below:
<?php
$id = $_GET["id"];
$review = $_GET["review"];
$url = 'http://edward/~treeves/ratingJSON.php';
$jsonData = array("id" => "$id", "review" => "$review");
$ch = curl_init($url);
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('json' => $jsonDataEncoded));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
?>
And posts it to the web service shown below:
<?php
header("Content-type: application/json");
try {
$conn = new PDO("mysql:host=localhost;dbname=treeves;", "treeves", "oopheiye");
$json = $_POST["json"];
$data = json_decode ($json, true);
$result = $conn->query("INSERT INTO poi_reviews (poi_id, review)
VALUES ('$data[ID]', '$data[review]')");
} catch (Exception $e) {
echo $e->getMessage();
}
?>
However the data being inserted is blank. When I use var_dump($data) on the web service is shows 1 NULL. I think it's to do with the variables in the CURL file as the web service works. Any ideas?
Update
Taking out the HTTP header and using 'var_dump($data, $error === JSON_ERROR_UTF8)' is returning the following:
array(2) { ["id"]=> string(4) "1014" ["review"]=> string(1) "2" } bool(false)
Here you set up form encoded data with one key (json) that has a value (of JSON encoded data):
curl_setopt($ch, CURLOPT_POSTFIELDS, array('json' => $jsonDataEncoded));
Here you tell the server that you are sending JSON and not form encoded data.
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
One of the above has to be wrong, since they are contradictory.
Here you try to read form encoded data:
$_POST["json"];
So claiming you are sending plain JSON is wrong (your JSON is encapsulated in form encoding).
Remove this line:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
Below is the code I am using
$decode = json_decode($json, true);
var_dump($decode);
This results in the below:
c.ak.instagram.com/hphotos-ak-xfa1/10666256_719752088073218_1127882203_a.jpg"
["full_name"]=> string(26) "Promote OLShop Harga Murah" ["bio"]=> string(0) "" ["id"]=>
string(9) "356515767" } } } }
How do I get Get Media ID?example results :
817757393383064097_356515767
Please help me.
$json = file_get_contents('https://api.instagram.com/v1/tags/gaul/media/recent?access_token=1463408808.e757b44.0738048e481448b48f1cbb23f70f0195&count=1');
$decode = json_decode($json, true);
$media_id = $decode['data'][0]['id']
If you took a look at Embedding you would find a suitable answer, for me i was in need for the media_id for a project, so i wrapped it into a function
function getMediaID($permalink) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.instagram.com/oembed?url=' . $permalink);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$oembed = curl_exec($ch);
curl_close($ch);
$oembed = json_decode($oembed, true);
return $oembed['media_id'];
}
That result you showed are when getting a USER data... not medias. To get media use some like:
https://api.instagram.com/v1/users/USERID/media/recent/?access_token=TOKEN&count=COUNT
Where:
USERID ir the user you want to get medias
TOKEN is your access token that enable you to use the API
COUNT to tell how much photos of that user you want to retrieve at this time
code by Bankzilla is working perfectly. I would upvote it , but for my reputation points are less :/. Also the code isnt echoing anything so the page will be blank.
Here is the code to display the media id. Copy it into a file with php extension for ex: getmedia.php and paste url where your are hosting it in browser and run it.
ex : www.myhost.com/mysite/getmedia.php?url="URL OF THE MEDIA HERE"
<?php
$permalink = $_GET["url"];
getMediaID($permalink) ;
function getMediaID($permalink) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.instagram.com/oembed?url=' . $permalink);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$oembed = curl_exec($ch);
curl_close($ch);
$oembed = json_decode($oembed, true);
echo $oembed['media_id'];
return $oembed['media_id'];
}
?>
You will use:
$search_response = curlRequest("get", "https://api.instagram.com/v1/users/self/media/recent/?access_token={$json_data['access_token']}");
Then:
$photo_id= $search_response['data'][$i]['id'];
echo $photo_id .'<br/>';
($i for exapmle data[1] , data[2] etc.) - (each image data)
I have script that calls at script via cURL. It looks like this,
Route::get('login-redirect', function() {
if (Input::has('error')) {
return Input::get('error_description');
}
if (Input::has('code')) {
$fields = array(
'grant_type' => 'password',
'username' => 'admin#local.com',
'password' => 'passwohrd',
'client_id' => 'testclient'
);
$fieldstring = http_build_query($fields, "\n");
$url = "http://apitest.local/api/v1/get-token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldstring);
$result = curl_exec($ch);
$json = json_decode($result);
curl_close($ch);
$fields = array('access_token' => '3c1e6b099f172fc01304403939edf8e56904ab61');
$fieldstring = http_build_query($fields, "\n");
$url = "http://apitest.local/api/v1/me";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldstring);
$result = curl_exec($ch);
curl_close($ch);
dd($result);
}
The json returned looks like this, if I do dd($json)
{"content":null,"error":true,"error_description":"Invalid username and password combination"}int(1)
I feel like after running it through json_decode I should be able to just output $json->error but no.
The JSON gets made in the following class, but I cannot see anything odd here either, I am doing incorrect, or do I misunderstand json_decode?
<?php
namespace Shaunpersad\ApiFoundation\Http;
use App;
use Response;
class ErrorResponse
{
public static function make($message = '', $status = 200, array $headers = array(), $options = 0)
{
$response = App::make(
'api_response_array',
array(
'content' => null,
'error' => true,
'error_description' => $message
)
);
return Response::json($response, $status, $headers, $options);
}
}
First of all, you do not have CURLOPT_RETURNTRANSFER - your curl_exec returns output buffer directly to the screen.
Second of all, it looks like you have var_dump somewhere and I cannot see where :)
Third of all - you didn't asked any direct question.
Edit
Okay i've read it few time and answer below. The dd() function is truly a var_dump wrapper but it is dumping var_dump data into json format afaics.
What you've got as an output is not from dd($json):
// this part has been output by curl_exec():
{"content":null,"error":true,"error_description":"Invalid username and password combination"}
// only this part comes from dd($json):
int(1)
Here's why:
// no CURLOPT_RETURNTRANSFER, so curl_exec() outputs result and returns true:
$result = curl_exec($ch);
// thus $result = true;
// so here $json = 1, since this is what json_decode(true) will return
$json = json_decode($result);
// then you did dd($json), so it just appended var_dump(1) to the output:
{"content":null,"error":true,"error_description":"Invalid username and password combination"}int(1)
Update
As stated in the other answers, you're not actually receiving the output because you haven't set CURLOPT_RETURNTRANSFER. So curl_exec() will echo out the response to the DOM and return true (1) as your curl request ran successfully.
You'll be able to run the below stuff by setting this in your curl request somewhere:
curl_setop(CURLOPT_RETURNTRANSFER, true);
dd() is a laravel function and this is what the documentation says:
Dump the given variable and end execution of the script.
I'd presume it is just a wrapper function for a prettier looking var_dump() (As I don't use laravel, I wouldn't know its exact output.).
What you want is to decode the $result that is returned from your cUrl. Something like this should suffice:
$data = json_decode($result);
echo $data->error_description;
The successfully decoded object looks like this:
stdClass Object
(
[content] =>
[error] => 1
[error_description] => Invalid username and password combination
)
Example
You can even test your boolean error value like this now:
if($data->error) {
//....true
} else {
//....false
}
Im trying to get some data into a string from an API..
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "https://api.feathercoin.com/?output=usd");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$result = curl_exec($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
// close curl resource to free up system resources
curl_close($ch);
?>
The above gives me: array(1) { ["usd"]=> float(1.210935) }
Now all I need to do is get the 1.210935 into a string of $coinvalue.
Can anyone help me do this?!!
Thank you
Jason
$result = json_decode($result, true);
$coinvalue = (string) $result["usd"];