PHP get variable from json results - php

Using PHP I have a json result of
{"text_block":[{"text":"XYZ","left":0,"top":0,"width":10,"height":12}]}
I can get this printed by the below code:
$json= file_get_contents('https://api.url');
$result = json_decode($json, true); //this returns an array
$result = json_decode($json);
$data = get_object_vars(json_decode($json));
$data = array_slice( $data, 0, 10 ); // now you can array functions
echo json_encode( $data );
but need to put the text "XYZ" into a variable for further use in PHP script. How can I do this, I've check various sources but don't seem to be getting anywhere! Thanks

$res = json_decode($data,true);
$my_text = $res['text_block'][0]['text'];
now you can use my_text as a variable

It looks like the value "XYZ" would be in
$data["text_block"][0]["text"]
Temporarily change the last line to var_dump($data) so you can get familiar with the php array structure.

Related

indexing JSON in php after removing item

How can I re-index a JSON after using unset($json -> nodes[$data_deleteNode]) to remove an entry? The common method array_values($json), which usally close the gaps doesn´t work. I understand the error message but do not have an idea to solve it.
array_values() expects parameter 1 to be array, object given
There is a similar thread which refers to the solutions I tried - PHP json_encode as object after PHP array unset() the only difference is the JSON.
If I do not perform any sorting, unset() adds an index which cause my JSON to be not readable for other scripts.
The affected PHP:
<?php
header("Access-Control-Allow-Origin: *");
$data_deleteNode = ($_POST['id']);
$json = file_get_contents("data2.json");
$json = json_decode($json);
//$data_deleteNode = json_decode($data_deleteNode);
//array_splice($json, 3, 1);
printf("%s\n", json_encode($json));
unset($json -> nodes[$data_deleteNode]);
printf("%s\n", json_encode($json));
$json = array_values($json);
$json = json_encode($json);
file_put_contents("data2.json", $json)
?>
UPDATE: modified playground which shows the error https://3v4l.org/XPbuo#v730
$json = file_get_contents("data2.json");
$data = json_decode($json);
unset($data->nodes[$data_deleteNode]);
$data->nodes = array_values($data->nodes);
$json = json_encode($data);
file_put_contents("data2.json", $json)
$data->nodes is the array you're modifying and that you need to reset. You do that with:
$data->nodes = array_values($data->nodes);
Note also that I renamed your variables so $json refers to JSON encoded text, and $data refers to decoded arrays/objects.

How do I get variable values from this JSON array?

So I have a URL that returns the following:
[{"_id":{"champ2_id":63,"champ1_id":2,"role":"TOP"},"count":4,"champ1":{"thirtyToEnd":0,"goldEarned":10727.5,"zeroToTen":0,"minionsKilled":158,"winrate":0,"assists":6.25,"role":"TOP","deaths":6,"kills":4,"wins":0,"totalDamageDealtToChampions":17350.75,"twentyToThirty":0,"tenToTwenty":0,"neutralMinionsKilledTeamJungle":1.75,"killingSprees":0.75,"weighedScore":27214.5375},"champ2":{"twentyToThirty":0,"wins":4,"winrate":1,"kills":5.75,"neutralMinionsKilledTeamJungle":5,"totalDamageDealtToChampions":21881.25,"role":"TOP","assists":7,"tenToTwenty":0,"thirtyToEnd":0,"zeroToTen":0,"goldEarned":12371.75,"killingSprees":1.25,"minionsKilled":140.5,"deaths":4.25,"weighedScore":33166.587499999994}]
I have learned how to get the value of a key in an array when the URL returns something simpler. For example if the URL returns:
{"id":34743514,"accountId":49161997,"name":"League of Fiddle","profileIconId":786,"revisionDate":1514093712000,"summonerLevel":52}
I can echo the id with this code:
$json = file_get_contents(URL);
$data = json_decode($json, true);
echo $data['id'];
That's easy. But when I try to use the same code for the more complicated stuff, like say I want to get the value of _id champ2_id, I've tried:
$json = file_get_contents(URL);
$data = json_decode($json, true);
echo $data['_id']['champ2_id'];
But this says _id is an undefined index. What am I doing wrong?
should be
$data[0]['_id']['champ2_id'];

How to take out int value from JSON object?

I'm working with Laravel 5 right now and I have the following problem. I've got response from DB query:
[{"id":1}]
and I want to take out 1 as int or string. Any ideas?
I've tried to solve this like follows:
$json = (DB query);
$data = json_decode($json);
$final = $data[0]->id;
and response is :
json_decode() expects parameter 1 to be string, array given
This is all you need.
$response = json_decode($response); // Decode the JSON
$string = $response[0]->id; // Save the value of id var
As you say, the string you have is in JSON format, so you need to use json_decode to access it in PHP.
The square brackets refer to an array, and the braces refer to an object within that array, so what you're looking for is the id value of the first element (i.e. element 0) in the array.
<?php
$json = '[{"id":1}]';
$data = json_decode($json);
echo $data[0]->id;
// 1
Try this
$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
You just need to decode it, if I'm not misunderstanding your questions.
$json = '[{"id":1}]';
$decodedObject = json_decode($json);
Then you can loop through the aray and do something with your data:
foreach($decodedObject as $key => $value) {
$id = $value->id;
}
If you're using Laravel, though, why not use Eloquent models?

GET info from external Array/API/URL using PHP

I have the url http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132 which leads to an array.
I want to get the value of the first 'sellorders' which in this case is: 0.00000048 and store it in the variable $sellorderprice.
Can anyone help?
Thanks.
Just access the url contents thru file_get_contents. Your page actually return a JSON string, to get those values into meaningful data, decode it thru json_decode, after that access the data needed accordingly:
$url = 'http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132';
$data = json_decode(file_get_contents($url), true);
$sellorderprice = $data['return']['DOGE']['sellorders'][0]['price'];
echo $sellorderprice;
That code actually points directly to index zero 0 which gets the first price. If you need to get all items an just simply echo them all you need to iterate all items thru foreach:
foreach($data['return']['DOGE']['sellorders'] as $sellorders) {
echo $sellorders['price'], '<br/>';
}
Its simple, you just have to decode json like this:
$json = file_get_contents("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132");
$arr = json_decode($json, true);
$sellorderprice = $arr['return']['DOGE']['sellorders'][0]['price'];

JSON decode with PHP: Key started with # sign

JSON is like
{
"#http_status_code": 200,
"#records_count": 200,
"warnings": [],
"query": { ... ...
In PHP
$data = json_decode($json_entry);
print $data->#http_status_code; //returns error
print $data->http_status_code; //returns nothing
How can I retrieve status code?
1) As Object way
$data = json_decode($json_entry);
print $data->{'#http_status_code'};
2) OR use as array way by passing second argument as true in json_decode
$data = json_decode($json_entry, true);
print $data['#http_status_code'];
Try json_decode to get the json in form of array ..
$json_array = json_decode($data, true);
$required_data = $data['required_key']
with reference to your particular problem .. you will get array as
Array
(
[#http_status_code] => 200
[#records_count] => 200
[warnings] => Array
(
)
....
)
so you can access you data as $data['#http_status_code']
To access an object property that has funky characters in the name, quote the name and stick it in braces.
print $data->{'#http_status_code'};
Or, say $data = json_decode($json_entry, true); to get the data back as an array.
PHP cwill give syntax error when you do this:
$data->#http_status_code;
it looks for $http_status_code variable which is not present
so in order to make this work you have to do this:
echo $data->{'#http_status_code'};
Try this:
$data = json_decode($json_entry, true);
print $data["#http_status_code"];

Categories