Retrieve string from json - php

I'm trying to retrieve a URL string from some json code.
Here is the json code
{"files":["www.example1.com"],"previews":["www.example1preview.com"],"meta":{},"userId":"guest","product":{"id":"2335","name":"standard"},"type":"u"}
Looking at what I've seen in the PHP manual I'm trying to retrieve previews like this.
<?php
ob_start();
include('getjson.php');
$meta_value_json = ob_get_clean();
echo $meta_value_json;
$meta_value_json = json_decode($meta_value_json);
print $meta_value_json->{'previews'};
?>
This doesn't seem to output the value however.

By experimenting with php -a command on terminal, I've put your json into json_decode and managed to get your link by just doing:
print $meta_value_json->previews[0];
The only reason to use print $meta_value_json->{'previews'}; at least according to php documentation is if you want an object as output and the key trying to retrieve is numerical or of a type that is not supported by php.
By experimenting a bit further, the reason that print $meta_value_json->{'previews'}; fails is because print expects a string, in our case here previews is an array. Therefore if you do print $meta_value_json->{'previews'}[0]; it will also work as expected.

You need to get the value from your decoded json like this: $class->parameter.
Knowing that previews is an array, you will also need to choose a specific element from it to print ( I got the first one ):
<?php
ob_start();
include('getjson.php');
$meta_value_json = ob_get_clean();
echo $meta_value_json;
$meta_value_json = json_decode($meta_value_json);
print $meta_value_json->previews[0]; /// get the specific value
?>

Related

Can not echo data from MYSQL database

Hello! The data in table is like that, and I cannot echo these entries individually. I want to show this data in HTML table like for example, Subject: Math, Correct: 34, Wrong: 6.
I am new in php, please help me with this case.
The data in the table seems to be in JSON format. You can convert it to a PHP object using json_decode() then print that object using print_r().
When put all together, you get
echo print_r(json_decode($data), true);
Note, I have to edit this response back to what it is now because #fenil-shah had changed it some something else that was not suitable. Please send your own response instead of making others say what they didn't intend to.
#fenil-shah, my answer was written the way it was on purpose. Here are the explanations:
In general, if you want to stay in control of the result of the print_r() function, you need to return its result as a string. That's why I have passed true as second parameter for the print_r() function. You wouldn't using print_r() without returning its result as a string in a middle of another script because it will output some text in an uncontrolled manner that can break an add. Once you have the return string, you can send it to a log file or do whatever you want with it.
json_decode works beautifully without passing it a true as second parameter. The OP's example is showing a object. You edit was purposely changing the decoded object to an array with associative array. Why?
You have removed the space after the comma which you had moved in from the print_r() to the json_decode() to make it look like json_decode($data,true). You need to know that the space was there for two reasons: Readability and Compliance with the PSR-2 standard (read more about that PHP coding standard at https://www.php-fig.org/psr/psr-2/#46-method-and-function-calls).
There are echo "",print_r() and print() function available in php to print data.If query is returning array then use print_r() function but if query is not returning anything or invalid fetch method in php then data is not getting display by any of these functions.
I think this is what you want as a output.
You can decode the JSON received from database using json_decode() function and get your result transformed in associative array.
Later on passing the array in foreach() loop will do your work accordingly
<?php
$result = '{
"30": {
"subject_id":343,
"correct_answers":34,
"wrong _answers":61,
"not_answered":0,
"time_spent":3801,
"time_to_spend":3680,
"time_spent_correct_ answers":3286,
"time_spent_wrong_answers":515
},
"52": {
"subject_id":52,
"correct_answers":7,
"wrong_answers":3,
"not_answered":0,
"time_spent":883 ,
"time_to_spend":94343,
"time_spent_correct_ans wers":352,
"time_spent wrong_answers":441
},
"53": {
"subject_id":53,
"correct_answers":3,
"wrong_answers":7,
"not_answered":43,
"time_spent":584 ,
"time_to_spend":900,
"time_spent_correct_ans wers":154,
"time_spent wrong_answers":430
}
}';
$json_decoded_data = json_decode($result,true);
?>
<table>
<tbody>
<tr>
<th>subject_id</th>
<th>correct_answers</th>
<th>wrong_answers</th>
</tr>
<?php
foreach($json_decoded_data as $row){
echo "<tr>";
echo "<td>".$row['subject_id']."</td>";
echo "<td>".$row['correct_answers']."</td>";
echo "<td>".$row['correct_answers']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>

How to echo the post value received in post

I'm using image uploader plugin which is posting data in multi dimension array like shown below
Array
(
[file] => {"input":{"name":"KE6Cc2ea2b584.jpg",
"type":"image/jpeg",
"size":61224,
"width":800,
"height":643},
"output":{"width":320,"height":180,
"image"
:"data:image/jpeg;base64,/9j/just an example of base 64 encoded image"},
"actions":{"crop":{"x":0,"y":96.5,"height":450,"width":800 },
"size":{"width":320,"height":320}}}
)
Now i tried lot to echo these post values like shown below
echo $_POST['file']; worked but brought all the data
echo $_POST['file']['output']; didn't worked
echo $_POST['file']['output']['image']; didn't worked
How can i get the value of these post
When trying to echo out any sort of values while debugging, it's a good idea to see exactly what you're getting via var_dump. For example, instead of your echo lines, I'd simply put:
echo "<pre>";
var_dump($_POST['file']);
Check your output there and it should show you exactly what keys you have to work with.
Also, depending on how your plugin is sending the data, you may not get any actual keys. According to your comment about $_POST['file'] printing all the output, it seems as though it's still a string. Try putting the JSON into an object, like so:
$test = json_decode($_POST['file']);
Or, if you'd prefer an associative array as mentioned:
$test = json_decode($_POST['file'], true);
Then get the output of $test:
echo "<pre>";
var_dump($test);

Grab, filter and show this data in PHP

This is example what I mean:
I wanna grab result from this url web1.com/do.php?id=45944
Example output:
"pk":"bn564vc3b5yvct5byvc45bv","1b":129,"isvalid":true,"referrer":true,"mobile":true
Then, I will show data result on other site web2.com/show.php
But I just wanna see data value "pk", "1b" and "isvalid". I don't need "referrer" and "mobile" data.
So, when I access web2.com/show.php, it just show data like this:
bn564vc3b5yvct5byvc45bv 129 true
file_get_contents web1.com/do.php?id=45944
Grab this result "pk":"bn564vc3b5yvct5byvc45bv","1b":129,"isvalid":true,"referrer":true,"mobile":true
Filter and show value "pk", "1b" and "isvalid" on web2.com/show.php
So, can you help me with simple php code/script?
Sorry if you don't understand because my english.
Is this source providing JSON-formatted data? That is, with { }'s around it?
If so, use PHP's built in json_decode function. (Man page at http://php.net/manual/en/function.json-decode.php) It will parse the JSON data for you and return an associative array. For example
$your_JSON_data = '{"pk":"bn564vc3b5yvct5byvc45bv","1b":129,"isvalid":true,"referrer":true,"mobile":true}';
$your_array = json_decode($your_JSON_data);
echo $your_array['pk'] . ' ';
echo $your_array['1b'] . ' ';
echo $your_array['isvalid'];
If, for some reason, there are no JSON-style curly braces around your data, you can append them.... for example,
$proper_JSON = "{$bad_json_data}";
however, if that's the case, I'd wonder why it wasn't properly formatted in the first place. In that case it may be safer to use the PHP explode function (http://php.net/manual/en/function.explode.php)

fetch array from a given url in php

i have a url.. eg http://www.example.com/index.php?rou=feed/web_api/categories&key=4&parent=0&level=10
when i hit the link simply on browser it displays a long list of multidimensional array.
I want to know that is it possible to store the url in a variable, something like this
$link=http://www.example.com/index.php?rou=feed/web_api/categories&key=4&parent=0&level=10
And then display the array in it as
echo '<pre>';
print_r($link);
echo '</pre>';
and then fetch the values from the array
I tried doing so but it displayed only a blank screen. Not sure if i am going on the right track. can anyone guide me
I think you are looking for one of these:
$data = file_get_contents('http://example.com/data.php');
This will fetch the raw data from the specified URL, and store the contents to the variable.
You may then need to implement your own code to actually parse the raw data, depending on your encoding type.

I'm fairly new to JSON, and I'm trying to get the user data from google + JSOn Code is

I'm fairly new to JSON, and I'm trying to get the user data from google +
JSOn Code is
https://www.googleapis.com/plus/v1/people?query=saurabh+sharma&key=AIzaSyADJjj8IeKuGb-woleHKTVouSlvAJUpTrs
Please help me to retrive the user profile.. in php
var_dump(json_decode(file_get_contents('https://www.googleapis.com/plus/v1/people?query=saurabh+sharma&key=AIzaSyADJjj8IeKuGb-woleHKTVouSlvAJUpTrs')));
It's indeed a bit of a mixed potato-puree (=confusion) between arrays and objects. That JSON is entirely object, except for the array 'items', which is an array of... objects.
Try this:
<?php
$strUrl = "https://www.googleapis.com/plus/v1/people?query=saurabh+sharma&key=AIzaSyADJjj8IeKuGb-woleHKTVouSlvAJUpTrs";
$strContents = file_get_contents($strUrl);
$objPeopleFeed = json_decode($strContents);
//It's an array of objects, so:
echo "<h1>{$objPeopleFeed->title}</h1>";
foreach($objPeopleFeed->items as $objUser)
{
echo "
<p>
<img src='{$objUser->image->url}' />
<a href='{$objUser->url}'>{$objUser->displayName}</a>
<i>{$objUser->objectType}</i>
</p>";
}
?>
What it does: It gets the contents from the web (which is JSON), interpretes it as JSON into valid PHP structures. From the structure, we print the title as a H1 header. From the items, which is an array, we loop through each one, print the image src from $objUser->image->url, print the user link $objUser->url with its name $objUser->displayName, and optionally its type of object $objUser->objectType that is registered on Google.
Because everything is kind of objects, you use the object to variable syntax '->xyz' instead of array indexes '["xyz"]', and I guess you got stuck there. The $objPeopleFeed->items is a non-associative array, so you use numbers to loop through the items ($objPeopleFeed->items[0] for the first item, 1 for the second, etc...). As a final cookie to you, you can use count($objPeopleFeed->items) as a results count.

Categories