How to return data using cURL call - php

This returns a token, like: {"token":"260e5b8adf74af6be5dfa250c5ad93c8"}
And I want just want the content part: 260e... Which I think I can get it by using $getInfo['token'], right?
$user="admin";
$password="Moodle15!";
$services="moodle_mobile_app";
$url = "https://localhost/moodle/login/token.php?username=".$user."&password=".$password."&service=".$services."";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURL_RETURNTRANSFER, true);
$getURL = curl_exec($ch);
$getInfo = json_decode($getURL, true);
$displayToken = $getInfo['token'];
echo $displayToken;
curl_close($ch);
And I don't know what's going on with the CURL_RETURNTRANSFER.
And the error:
Notice: Use of undefined constant CURL_RETURNTRANSFER - assumed 'CURL_RETURNTRANSFER' in C:\xampp\htdocs\moodle\cURL_script.php on line 12
Warning: curl_setopt() expects parameter 2 to be long, string given in C:\xampp\htdocs\moodle\cURL_script.php on line 12
{"token":"260e5b8adf74af6be5dfa250c5ad93c8"}
EDITED:
And if I had:
{"id":4,"username":"Jhon","firstname":"smith","lastname":"Reches","fullname":"Jhon smith","email":"Jhon.smith#example.com","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/25\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/25\/user\/icon\/f1","groups":[],"roles":[{"roleid":5,"name":"","shortname":"student","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"},{"id":2,"fullname":"Grup de Recerca","shortname":"Grp. Recerca"}]}
How can I acces to 'username'? or 'fullname' when you know there are many 'fullname' in it?
EDITED2:
New code I have now:
$token = "260e5b8adf74af6be5dfa250c5ad93c8";
$funcion="core_enrol_get_enrolled_users";
$courseid="3";
$format="json";
$url= "https://localhost/moodle/webservice/rest/server.php?wstoken=".$token."&wsfunction=".$funcion."&courseid=".$courseid."&moodlewsrestformat=".$format."";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$getURL = curl_exec($ch);
$getInfo = json_decode($getURL, true);
$email = $getInfo[2]['email'];
echo $email."</br>";
curl_close($ch);
Now $email contains jhon.smith#example.com but I have many results, how can I manage to display all of them with a foreach? Because it is a multidimentional array. See below.
[{"id":4,"username":"jhon1.smith1","firstname":"Jhon1","lastname":"Smith1","fullname":"jhon1 smith1","email":"jhon1.smith1#example.cat","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/25\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/25\/user\/icon\/f1","groups":[],"roles":[{"roleid":5,"name":"","shortname":"student","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"},{"id":2,"fullname":"Grup de Recerca","shortname":"Grp. Recerca"}]},{"id":5,"username":"jhon1.smith1","firstname":"Josep","lastname":"jhon1 ","fullname":"jhon1 smith1","email":"jhon1.smith1#example.cat","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/26\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/26\/user\/icon\/f1","groups":[],"roles":[{"roleid":5,"name":"","shortname":"student","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"},{"id":2,"fullname":"Grup de Recerca","shortname":"Grp. Recerca"}]},{"id":6,"username":"jhon1.smith1","firstname":"jhon1","lastname":"smith1","fullname":"jhon1 smith1","email":"jhon1.smith1#example.cat","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/32\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/32\/user\/icon\/f1","groups":[],"roles":[{"roleid":1,"name":"","shortname":"manager","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"},{"id":2,"fullname":"Grup de Recerca","shortname":"Grp. Recerca"}]},{"id":7,"username":"jhon1.jhon1","firstname":"jhon1","lastname":"jhon1","fullname":"jhon1 smith1","email":"jhon1.smith1#example.cat","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/35\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/35\/user\/icon\/f1","groups":[],"roles":[{"roleid":5,"name":"","shortname":"student","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"}]},{"id":8,"username":"jhon1.smith1","firstname":"jhon","lastname":"smith1","fullname":"jhon1 smith1","email":"jhon1.smith1#example.cat","department":"","firstaccess":0,"lastaccess":0,"description":"","descriptionformat":1,"profileimageurlsmall":"http:\/\/localhost\/moodle\/pluginfile.php\/41\/user\/icon\/f2","profileimageurl":"http:\/\/localhost\/moodle\/pluginfile.php\/41\/user\/icon\/f1","groups":[],"roles":[{"roleid":3,"name":"","shortname":"editingteacher","sortorder":0}],"enrolledcourses":[{"id":3,"fullname":"Game Design","shortname":"Game Design"}]}]
and I wish:
foo#example.com
bar#example.com
foo2#..

CURL_RETURNTRANSFER needs to be changed to CURLOPT_RETURNTRANSFER.
That is affecting what is returned by curl_exec() so you aren't getting the JSON string in $getURL.
Once the constant is corrected, the rest of your code is correct.
EDIT (added):
When dealing with JSON, it helps to format it so it's easier to read, I use jsonlint.com.
Then looking at the structure, if you had:
$data = json_decode($response, true);
Accessing the fullnames from enrolledcourses would be:
echo $data['enrolledcourses'][0]['fullname'];
Or if you were using object notation, rather than associative array:
echo $data->enrolledcourses[0]->fullname;

Related

How to extract and access data from JSON with PHP when some data changes?

I am trying to bring in some API data to a directory in wordpress.
The data I am trying to get is just crypto coin price, none of the other information but because its format is sort of nested (?) it doesnt seem to work.
{
"bitcoin": {
"usd": 16808.82
}
}
This is my code so far:
<?php
$handle = curl_init();
$url = get_post_meta($entity-\>post()-\>ID, '\_drts_field_004', true);
// Set the url
curl_setopt($handle, CURLOPT_URL, $url);
// Set the result output to be a string.
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($handle);
curl_close($handle);
$data = json_decode($output);
echo $output;
var_dump($data);
The results are:
{
"bitcoin":{
"usd":16833.02
}
}
object(stdClass)#10399 (1) {
["bitcoin"]=> object(stdClass)#10492 (1) {
["usd"]=> float(16833.02)
}
}
In this example I am only after the 16833.02
I am trying to do this for lots of different coins, the "usd" will always be the same but the "bitcoin" will change when other coins.
How can I echo only the number?
I have tried lots of variations of echo but cannot get it? Is it possible to do something like:
echo $data['bitcoin']['usd'];
but rather than bitcoin use * ?
As in anything can be there?
You can access the usd value by decoding the JSON to an array instead of an object like this
$data = json_decode($output, true);
$usd = current($data)['usd'];

how to pass dynamic URL to curl in php - getting error 1

I'm trying to pass a $url to curl using a function.
the URL is built with a variable in it in the following method:
a.php // main page, include (a.php, b.php)
b.php // dynamic string function
c.php // curl function
I build a dynamic string successfully using sessions data // $_SESSION["input"]
myDynamicstringfunction set a string by multiple sessions input values.
$dval = myDynamicstringfunction();
echo $dval;
// render correctly to: "-e5 -g6 -g7"
the $dval value is a string that resolve as expected. the $url is:
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 $dval";
The $url is render correctly with the
echo $url;
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 -e5 -g6 -g7";
I pass the $url to the curl function using:
$r = mycUrlfunction($url);
The curl function I use:
function singleRequest($url){
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$curly = curl_exec($ch);
if ($curly == FALSE){
die("cURL Error: " . curl_error($ch));
}
$result = json_decode($curly, true);
// close cURL resource, and free up system resources
curl_close($ch);
echo '<pre>';
return ($result);
}
The above get me an error (curl 1) - CURLE_UNSUPPORTED_PROTOCOL (1)
I have tried many things to get the $url to work with no success.
if I set the $url value manually without the $dval variable like this:
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 -e5 -g6 -g7";
The code works just fine and I get the correct results from the API call.
I tried using different quotes, {}, [], encoding to ASCII, vprintf(), and other solutions with no success.
the problem was with constructing the dynamic variable $dynamicstring of the URL
initially used
$dynamicstring= "-a" . $_SESSION["a"]." -b".$_SESSION['b']." -c".$_SESSION['c']." -d".$_SESSION['d']."<br>";
this have a few problems
when using echo it render the expected output correctly
it have a "<br>" at the end
it have the wrong structure
the correct way to construct the $dynamicstring is to use {}
$dynamicstring= "-a{$_SESSION["a"]} -b{$_SESSION['b']} -c{$_SESSION['c']} -d{$_SESSION['d']}";

Steam API load the items json

Hello guys i started to try use Steam API and i already done login... but i have a big problem to get items. I cant find solution what im doing wrong.
$GetClientSteamItemsUrl = " http://steamcommunity.com/profiles/" . $_SESSION['steam_steamid'] . "/inventory/json/730/2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GetClientSteamItemsUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 3);
$output = curl_exec($ch);
$ArrayInventory = json_decode($output, true);
foreach($ArrayInventory['rgDescriptions'] as $inventory)
{
echo $inventory;
}
On that link is my items that i want to write their name on my page.
Error: Warning: Invalid argument supplied for foreach() in /data/web/virtuals/112855/virtual/www/subdom/ayy/index.php
Can someone help me to select specific part of code?
Try this
$inventory = file_get_contents("http://steamcommunity.com/profiles/".$_SESSION['steamid']."/inventory/json/730/2");
$myarrayInv = json_decode($inventory, true);
foreach($myarrayInv['rgDescriptions'] as $item)
{
echo $item['name'];
}
if you want icon_url etc. do $item['icon_url'], hope this helps.

How to send JSON and retrieve it using cURL?

This link = http://localhost/api_v2/url?key=***
will return this list of JSON :
I've already tested by :
Navigate to http://localhost/api_v2/url?key=*** through a browser
And make a curl request via command line $ curl http://localhost/api_v2/url?key=***
either way will give return the JSON, and give me the same result.
Well, what I can tell by that is my $array is storing something in it.
Even if I did dd($array) - I still get the same result.
Here is what I've
Here is how I establish my JSON
public function index_2(){
$file_name = 'inventory.csv';
$file_path = 'C:\\QuickBooks\\'.$file_name;
$csv= file_get_contents($file_path);
$utf8_csv = utf8_encode($csv);
$array = array_map("str_getcsv", explode("\n", $utf8_csv));
return Response::json($array);
}
Here is how I make a cURL request and trying to retrieve that JSON
<?php
$ch = curl_init("http://localhost/api_v2/url?key=***");
curl_setopt($ch, CURLOPT_USERPWD, "admin:*****");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$body = curl_exec($ch);
curl_close($ch);
$json_decode = json_decode($array, TRUE);
I keep getting complaint that $array variable is not define, but in fact I did define and send it over like this return Response::json($array); .
I am not sure what I did wrong here.
Spot the difference:
$body = curl_exec($ch);
^^^^^
$json_decode = json_decode($array, TRUE);
^^^^^^

Google maps response's language issue

I'll try to be short: if you need more info, I'll tell you.
I'm using this code to get infos from Google Maps:
<?php
function getData($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0); //Change this to a 1 to return headers
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = 'http://maps.google.com/maps/geo?output=xml&q=' . urlencode($startPlace);
$url = 'http://maps.google.com/maps/api/geocode/json?sensor=false&gl=IT&address=' . urlencode($startPlace);
$xml = simplexml_load_string($this->getData($this->url)) or die("Error loading xml data");
$points = $xml->Response->Placemark->Point->coordinates;
$provincia = $xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->SubAdministrativeAreaName;
$regione =$xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;
echo $regione."<br>";
preg_match_all("/-*[0-9.]*(?=,)/", $points[0], $matches);
$longitude = $matches[0][0];
$latitude = $matches[0][2];
The code is used to retrieve infos about italian locations and till three days ago, all worked fine, but this morning I saw something strange: $regione returned by code ($xml->Response->Placemark->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;) had an english name.
Let's say the location found be a little town in Lombardia (where 'Lombardia' is the name of the Administrative Area), the Administartive Area name returned by Google Maps was no more 'Lombardia' but 'Lombardy'.
Since this data is used to search in a local database other places in the Administrative area and since the name used in the database is obviously italian name, application doesnìt work anymore.
I'll be grateful for any advice
The problem is solved using a different url, specifying language parameter:
'http://maps.google.com/maps/api/geocode/xml?sensor=false&language=IT&address=' . urlencode($startPlace);
This url type return correct results but defferently formed so it is necessary change the code to access the infos and put them into variables, but this solved my problem

Categories