Cant Grab data in API due to array - php

So it is pretty simple but I am having some difficulty.
I am grabbing data from an API and echoing it to the page using PHP and it is working.
However, not when the API data is wrapped in an 'array' or '[]'.
API 1: (WORKING)
{
"data": 18,
"data2": 20,
}
API 2: (NOT WORKING)
[
{
"data": 18,
"data2": 20,
}
]
My PHP code:
<?php
$url = "my correct url is here";
$json = json_decode(file_get_contents($url), true);
$dataprint = $json["data"];
echo $dataprint;
?>
Why is the simple change of '[]' messing the code up and not allowing me to print the information?

The square brackets are JSON notation for an array 'without' keys (In the decoded php array keys are numeric start with 0, and don't skip any numbers). You can access the data if you adjust one line in your code (add [0]):
$dataprint = $json[0]["data"];

Related

Read a JSON data value with mixed number and letter in key in PHP

I am stuck with this issue. I am trying to read data from openweathermap.org weather data API. One of the values, rainfall amount, is keyed with a digit and letter in the key. And PHP is throwing errors at me if I try to read it. Here is the code I'm trying to use.
$rainAmount = $data->hourly[$hour]->rain->1h;
and here is the JSON file (a portion of it anyways).
"rain": {
"1h": 1.78
}
This is data provided by the API so I can't just change the key that's used. Here is the PHP error
PHP Parse error: syntax error, unexpected integer "1", expecting identifier or variable or "{" or "$" in /home/
It's pretty obvious it is the digit in the key that is the issue. But how else do I read the value?
Thanks in advance.
Did you try:
$string = '{
"rain": {
"1h": 1.78
},
}';
$arr_weather = json_decode($string, true);
print $arr_weather['rain']['1h'];
The second parameter from json_decode(,, true is a bool to decode the data as an associative array. Please read more here about json_decode:
https://www.php.net/manual/en/function.json-decode.php
If you still want to work with your response as an object you can use the curly braces like this:
$string = '{
"rain": {
"1h": 1.78
},
}';
$weatherObject = json_decode($string);
print $weatherObject->rain->{'1h'};
But in this case, you have to know that if your key is a number only, it will not work, like $weatherObject->rain->{'12'} - So I recommend using the data as an array, like in the first example.

How to access a single json post via an url parameter using php?

I am currently stuck with this problem while trying to create a RESTFUL API using PHP without any frameworks or databases. I parsed the JSON data with PHP, but I am having trouble with trying to access a certain post depending on what query parameter you type to the URL.
So this is my php code:
<?php
header('Access-Control-Allow-Origin: *');
header ('Content-Type: application/json');
$jsondata = file_get_contents("credits.json");
print_r(json_encode($jsondata));
?>
And this is my json data:
{
"credits": [
{
"creditId": 123,
"id": 1,
"client": "Peter",
},
{
"creditId": 789,
"id": 2,
"client": "Jonas",
}
]
}
For instance: if my URL looks like this: http://localhost:5041/credits/, typing http://localhost:5041/credits/?id=1 would access only a single post with the certain id.
$data = '{
"credits": [
{
"creditId": 123,
"id": 1,
"client": "Peter"
},
{
"creditId": 789,
"id": 2,
"client": "Jonas"
}
]
}';
$data = json_decode($data,true);
$row = array_keys(array_combine(array_keys($data['credits']), array_column($data['credits'], 'id')),$_GET['id']);
if(isset($_GET['id'])){
print_r($data['credits'][$row[0]]);
}
else{
print_r($data);
}
First step is to decode your json into an array. Then using the php array functions i am searching in your multidimensional array for the value that you receive from your url using $_GET['id'] and print only the block that has this id , otherwise print the whole array.
Just like you asked your url will work for all the results if you don't put any id and will work for the specific results that belong to this id if you set an id in the url.

How to correctly parse JSON in PHP

I want to parse values from an Json API, but I cant get it to work
The API returns this JSON:
[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]
I tried to get the ID value like this:
$json_obj = json_decode($resp);
print $json_obj->assets[0]->id;
but I get no result whereas it should be 6. What do I do wrong here?
Remember the outer part of the JSON is an array, as suggested by the opening [. So you need to first access the first (and only) element of it:
$json_obj[0]->assets[0]->id; //<-- note the first [0]
I think the correct answer is
$json_obj = json_decode($resp);
print $json_obj[0]->assets[0]->id;
The json object will be converted to a php array, since you have an array with a object inside in your case it will be a multidimentional array with the objects inside.
Try this its worked for me..
$json ='[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]';
$json_obj = json_decode($json);
var_dump($json_obj[0]->assets[0]->id)
?>
decode JSON to the array and fetch the id by proper array keys
$jToArray = json_decode($resp, TRUE);
echo $jToArray[0]['assets'][0]['id'];//You will get the correct id

How to fetch an Array from MySQL with PHP

In my database I have POSTed following JSON with REST API:
{
"author": "Someone",
"hero_name": "Iron Man",
"hero_desc": ["Iron", "Man"],
}
Now in database Table, the entry says only Array for the hero_desc.
I cannot figure out how to get the actual items in that array.. for example to fetch Iron from hero_desc.
Here is how it gets returned with GET request:
{
"id": "11",
"user_id": "1",
"author": "Someone",
"hero_name": "Iron Man",
"hero_desc": "Array",
}
I am quite new to PHP so I am worried that I would need to mess up my whole app architecture to get this to work. I though PHP can handle fetching arrays by default if it sees it's an JSON Array.
use json_decode(); function for change json to array
$json_to_array = json_decode($your_json_variable_name);
You could change array data to JSON with json_encode In one hand you have an array without the key that code makes a number key for that in another hand if have an array with the key you can get that inside JSON with that key.
$content ='your content or your array data';
header('Content-Type: application/json; charset=utf8');
echo json_encode($content);

Get specific data in variable array JSON with jQuery PHP

I'm trying to get specific data from a JSON file (url) and save that data in a PHP variable.
The JSON comes from an url. For example:
https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Viducius?api_key=secret
The JSON file:
{
"viducius": {
"id": 26541044,
"name": "Viducius",
"profileIconId": 591,
"revisionDate": 1480517139000,
"summonerLevel": 30
}
}
So my question is how can I get the data from id, in this case 26541044, and put that into a PHP variable?
Also to get the data from the JSON file, I have to search for the id while the array name 'viducius' came from a PHP variable.
TLDR:
The array $arrayName contains an id '26541044' that has to be saved into variable $id
Is there someone who can help me with this? I was thinking on doing this in jQuery but if it's easier with PHP only thats fine too.
That is a JSON String, therefore you need to convert it into a PHP data structure. PHP Provides json_decode() to do that.
$json_string = '{"viducius": {
"id": 26541044,
"name": "Viducius",
"profileIconId": 591,
"revisionDate": 1480517139000,
"summonerLevel": 30
}
}';
$obj = json_decode($json_string);
$id = $obj->viducius->id;
echo 'id = ' . $id;

Categories