I know it's basic, but I couldn't get what's wrong because it's not my area.
I am sending some request to a server and print the response like this:
$rest = curl_init();
curl_setopt($rest,CURLOPT_URL,$url);
curl_setopt($rest,CURLOPT_GET,1);
curl_setopt($rest,CURLOPT_HTTPHEADER,$headers);
curl_setopt($rest,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($rest,CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($rest);
$json = json_decode($response, true);
echo $response;
Where I get this:
{"results":[{"Devices":["52401E7E-C5D7","AE80C0F8-999E","764BFD92-9753","78A23379-2C14","EEA03545-5EB9","E18DDFEC-C3C9"],"UserID":"433011AC-228A-4931-8700-4D050FA18FC1","createdAt":"2015-11-04T15:06:33.564Z","objectId":"3os7BGxRoG","updatedAt":"2015-11-04T17:08:57.635Z"}]}
Then, I am trying to print the JSON or its fields, but I then get nothing:
echo $json;
echo $json['UserID'];
echo $json['Devices'];
To clarify the comments a bit:
$str = '{"results":[{"Devices":["52401E7E-C5D7","AE80C0F8-999E","764BFD92-9753","78A23379-2C14","EEA03545-5EB9","E18DDFEC-C3C9"],"UserID":"433011AC-228A-4931-8700-4D050FA18FC1","createdAt":"2015-11-04T15:06:33.564Z","objectId":"3os7BGxRoG","updatedAt":"2015-11-04T17:08:57.635Z"}]}';
$json = json_decode($str, true); // to an associative array
// to echo the UserID
echo "userID : " . $json['results'][0]['UserID'];
// output: userID : 433011AC-228A-4931-8700-4D050FA18FC1
// to get the structure of the json array in general use print_r() as AbraCadaver pointed out
print_r($json);
In your attempt you were missing the results[0] part.
Related
I'm trying to understand how to record the result of a curl GET request using php. I'm looking at outputing part or all of the result to mysql.
https://github.com/cloudtrax/docs/blob/master/api/code/php/simple_api_server_test_harness.php
function invoke_curl($method, $endpoint, $headers, $json) {
$api_server = 'https://api.cloudtrax.com';
try {
// get a curl handle then go to town on it
$ch = curl_init($api_server . $endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if ($result == FALSE) {
if (curl_errno($ch) == 0)
echo "#### NOTE ####: nil HTTP return: This API call appears to be broken" . "\n";
else
throw new Exception(curl_error($ch), curl_errno($ch));
}
else
echo "RESULT: \n" . $result . "\n";
}
The $result shows like this:
{
"clients": {
"ssid2": 4,
"ssid1": 10
},
"rows": [
{
"time": "2016-03-23T02:45:00Z",
"ssid2": {
"traffic": {
"unclassified": {
// etc...
How can I associate each part of the result too a variable so I can then input too mysql?
It looks like this result in json format. You can use json_decode to decode it:
$resultObject = json_decode($result);
$clients = $resultObject->clients;
// ... get other data from result
The code below will convert the json into a PHP array. You can then use the indexes of the array to pull out values.
$result = json_decode($result);
$clients = $result->clients;
// Some MySQL queries
If your response is a JSON response then you can simply use php's json_decode to get parsed object.
$result = curl_exec($ch);
//to get associative array passing true
$jsonObj = json_decode($result, true);
$clients = $jsonObj['clients'];
$rows = $jsonObj['rows'];
You can refer to these answers for more detail:
Parsing JSON object in PHP using json_decode and
Parsing JSON file with PHP
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);
^^^^^^
Help me to grab name of games from url
This page output json format.
I try to convert it to array, but my code not work. Please help me!
$url = 'https://search.g2a.com/items/select?json.wrf=jQuery111003403934023808688_1411464896728&q=NOT+type%3Aindividual+AND+(-type%3Agaming+AND+wholesaleQty%3A%5B1+TO+*%5D+AND+wholesaleMinPrice%3A%5B0+TO+198%5D)&wt=json&start=0&rows=10000&sort=sortOrder+DESC&_=1411464896757';
$content = file_get_contents($url);
$json = json_decode($content, true);
echo "<pre>";
print_r($json);
echo "</pre>";
You should remove the JSONP parameter json.wrf from the URL first:
https://search.g2a.com/items/select?q=NOT+type%3Aindividual+AND+(-type%3Agaming+AND+wholesaleQty%3A%5B1+TO+*%5D+AND+wholesaleMinPrice%3A%5B0+TO+198%5D)&wt=json&start=0&rows=10000&sort=sortOrder+DESC&_=1411464896757
This will return a proper JSON result.
The output from that URL (that I get currently starts with):
jQuery111003403934023808688_1411464896728({"responseHeader" ...
This isn't a pure JSON response, but rather a JSONP response.
If you're just trying to parse it in PHP, maybe something like:
$url = ...; // Your URL Here
$data = file_get_contents($url);
$pos = strpos($data, '{');
$data = substr($data, $pos, strlen($data) - $pos - 2);
$json = json_decode($data, true);
echo "<pre>";
print_r($json);
echo "</pre>";
So I'm having a problem with the following code.
I've got CURLOPT_RETURNTRANSFER set to true, yet nothing is returned when curl_exec is hit. Any and all help is appreciated!
<?php
$yql_base_url = "http://query.yahooapis.com/v1/public/yql?q=";
$yql_query = "select * from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=YHOO,GOOG,AAPL&f=sl1d1t1c1ohgv&e=.csv' and columns='symbol,price,date,time,change,col1,high,low,col2'";
$yql_params = "&format=json&diagnostics=true&callback=";
$yql_url = $yql_base_url . urlencode($yql_query) . $yql_params;
$session = curl_init($yql_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($session);
curl_close($session);
$phpObj = json_decode($json);
if(!is_null($phpObj->query->results))
{
echo $phpObj->query->results;
}
?>
$phpObj->query->results is an array of Object and you can not do echo on it. Simply use print_r() or var_dump() on it.
Example:
print_r($phpObj->query->results);
var_dump($phpObj->query->results);
I have a php function that fetches and returns tweets data from twitter as simplexml object.I could get its contents by using php syntax. Here is php function
<?php
function searchResults($q) {
$host = "http://search.twitter.com/search.atom?q=" . urlencode( $q ) . "&rpp=100";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//Raw xml
$result = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($result);
return $xml;
}
?>
If I call it like
$xml = searchResults('xyz');
I could fetch its contents like
echo $xml->content.''.$xml->author->name;
Now I need to return it from php function in JSON format. Like
return json_encode($xml);
in spite of
return $xml;
So how do now I get same 'content' and 'author->name' etc contents from it in JSON format when I decode json.
If you don't need the XML for any other reason than to return it as JSON, why not use json format as the response for the Twitter API call?
http://search.twitter.com/search.json?q=blablabla
This returns the response in a JSON string that you could just return.
I would rewrite your code like this:
<?php
function searchResults($q) {
$host = "http://search.twitter.com/search.json?q=" . urlencode( $q ) . "&rpp=100";
$raw_json = file_get_contents($host);
return $raw_json;
}
?>
It depends. If you're accessing it back from PHP, there are two ways:
$obj = json_decode($json);
echo $obj->author->name;
or
$arr = json_decode($json, true);
echo $arr['author']['name'];
If you are accessing it using JavaScript, it should be:
alert(jsObject.author.name);