I'm using a php library from https://sourceforge.net/p/wowarmoryapi/home/Home/. It pulls json data from battle.net and stores it in my database for cache reasons.
code to get json from db (I'm not sure if it's still considered json at this point):
$data = $con->query('SELECT Data FROM wa_guilds');
I use the following code to see the data:
foreach($data as $row) {
echo "<span style='color:#ff0099'>";
var_dump($row);
echo "</span>"; }
which looks like this minus the errors, that's from another code:
I've tried various methods, mostly from this site to show my data in a way that's easy to read but I always get error.
This is definitely an object. if (is_object($data)) { echo "yay!"; } <--this works
Once I use $decodedjson = json_decode($data); it's no longer an object and I can't seem to print the results to see what it looks like. var_dump($decodedjson) returns NULL
Finally, when I use the following code:
foreach ($data as $da){
echo $da['Data']['character']['name']; }
returns Warning: Illegal string offset 'character'
and:
foreach ($data as $da){
echo $da['character']['name']; }
returns Notice: Undefined index: character
I don't understand what I'd doing wrong, or right. Do I need to somehow turn $data into a string?
NEW CODE
$sth = $con->query('SELECT Data FROM wa_guilds');
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row) {
foreach($row as $r) {
$myData = json_decode($r, true);
echo "<span style='color:#ff0099'>";
var_dump($myData['Data']);
echo "</span>"; } }
NEW ERROR
NULL NULL
From the warning I'm guessing you're using PDO. If $con is your PDO instance representing a connection to a database, try the following:
$sth = $con->prepare('SELECT Data FROM wa_guilds');
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row) {
$myData = json_decode($row['Data'], true);
echo "<span style='color:#ff0099'>";
// $myData should now be a PHP array which you can access easily
print_r($myData);
echo "</span>";
}
You will need to convert the json string first, I'm not sure how many rows you are expecting from the DB but if it's only one you don't need the loop:
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$decoded = json_decode($data['Data'], true);
echo "<span style='color:#ff0099'>";
var_dump($decoded);
echo "</span>";
if you need a loop it should work like this:
foreach($data as $d)
{
$decoded = json_decode($d['Data'], true);
echo "<span style='color:#ff0099'>";
var_dump($decoded);
echo "</span>";
}
Related
i want to print data which is coming from api when i print data it print only one data at a time how to print all these data in foreach loop i am using this but not work and getting and error Trying to get property 'Name' of non-object how to solve this problems thanks in advance
this is the response
this is my code
$response = sabreApiCall($url, $data_array);
$results = json_decode($response);
$i =0;
foreach ($results->GeoSearchRS->GeoSearchResults->GeoSearchResult[$i] as $hotel)
{
echo $hotel->Name;
$i ++;
}
}
Just return $results as laravel will return it as json.
why are you using $i variable to loop through this array. Simply use foreach like this
$response = sabreApiCall($url, $data_array);
$results = json_decode($response);
foreach ($results->GeoSearchRS->GeoSearchResults->GeoSearchResult as $hotel)
{
echo $hotel->Name;
}
}
I'm using iTunes RSS generator to get HOT tracks, now I'm using following way to parse JSON:
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'][0]['collectionName'];
echo $cltn;
?>
Now, as we know that It'll return only 1 collectionName.
JSON request is returning 10 results. How can I get them all using foreach loop? I've used several ways but no success.
Since you didn't give the output of the array I assume the [0] index is what needs to be iterated.
You need to foreach the $obj['feed']['results'] by doing:
Foreach($obj['feed']['results'] as $cltn){
Echo $cltn['collectionName'];
}
Foreach over the results:
foreach ($obj['feed']['results'] as $result) {
echo $result['collectionName'] . '<br>' . PHP_EOL;
}
Based on the code you provided you can iterate the results to get all possible information from the artist/track list, for example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
function test_print($item, $key)
{
echo "<strong>".$key."</strong>: ".$item."<br>";
}
foreach($cltn as $key => $c) {
echo "Result No ".($key+1)."<br>";
array_walk_recursive($c, 'test_print');
}
in case you only want to show artistName and collectionName you can slightly modify the above example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
foreach($cltn as $c) {
echo $c['artistName'].": ".$c['collectionName']."<br>";
}
You can try all the above in PHP Fiddle
Try like this way with foreach() to iterate your array in key=>value manner as you've decoded the json as an array not an object in php.
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$array = json_decode($jsondata,true);
# printing resulted array just for debugging purpose
print '<pre>';
print_r($array);
print '</pre>';
foreach($array['feed']['results'] as $key=>$value){
echo $value['collectionName'].'<br/>';
}
?>
i'm new in PHP language. I'm writing a PHP script to get information from my online database(created on my altervista personal webpage) and convert in JSON format.
The problem is about when i get elements from my database i can show them correctly using "echo" command, but when i parse associative array to "json_encode" function i can't see correctly elements.
Here is the code:
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
foreach($row as $key => $value) {
echo "" . $key . ": " . $value;
echo "<br>";
$json_array[] = array(''=>$key, ''=>$value);
}
} else {
echo "0 results";
}
echo json_encode($json_array);
$conn->close();
?>
The $result->fetch_assoc(); returns an associative array.
As i said before i can see correct information using echo commands.
The problem is when i use this:
$json_array[] = array(''=>$key, ''=>$value);
The output is as follow:
[{"":"Mark"},{"":"ABC"},{"":"25"}]
Basically it's showing me only the second parameter "=>$value", while the first parameter "=>$key" is ignored.
Can you tell me please what should i change in order to see also the first parameter in my output?
Thanks
The correct way would be to do that
$json_array[] = array( $key => $value );
instead of
$json_array[] = array(''=>$key, ''=>$value);
You are essentially adding an EMPTY string as key and the $key as value at first, and then you replace it with the $value as they share the EMPTY string key in the array.
Read more at: http://php.net/manual/en/language.types.array.php#language.types.array.syntax.array-func
First param is ignored because it has the same key as the second (the key is ''), you should write:
$json_array[] = array($key, $value); // Indexed array
Output will be:
[["key1", "value1"],["key2", "value2"],["key3", "value3"]]
OR
$json_array[] = array($key => $value); // Associative array
Output will be:
[{"key1": "value1"},{"key2": "value2"},{"key3": "value3"}]
Try:
sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$json_array[] = $row;
}
} else {
echo "0 results";
}
echo json_encode($json_array);
$conn->close();
In your code you are parsing only the first db result
I have the following problem. When i am trying to read some json data that are posted from an html page, i'm facing with the following error "Trying to get property of non-object on line".
Jquery script to create the json
var json = {"data":[]};
json.data.push({serialNumber: $serialNumber, xreosi: $xreosiToPost,
forma: $forma, apolia: $apolia});
Jquery for posting to php
$.post("page.php",{jsonData: JSON.stringify(json),
customer: $("#cusID").val()},function(data){});
PHP file
$json = json_decode($_POST['jsonData']);
foreach($json as $value){
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
Thanks in advance.
Thereafter:
var json = {"data":[]};
json.data.push({serialNumber: $serialNumber, xreosi: $xreosiToPost,
forma: $forma, apolia: $apolia});
You have:
Object[data][0] = array('serialNumber' => ...);
Need:
$json = json_decode($_POST['jsonData'][0]);
or
$json = json_decode($_POST['jsonData']);
foreach($json as $row){
foreach($row as $value) {
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
}
json_decode without second parameter returns result as php object. You have to pass true as second parameter. Also your data are in $json['data'], not $json:
$json = json_decode($_POST['jsonData'], true);
foreach($json['data'] as $value) {
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
What my code does:
I am returning arraylist from a php method -->method name:- getSubjectInfo().
And in my (Index.php) page i am getting this arraylist values in a $results variable. Here i am stuck how to iterate the arraylist values in the index.php page?.
My Problem: How to iterate the arraylist ($results) in my index.php page? Please see my below mention code
i have used $results = $sub_info->fetchAll(PDO::FETCH_OBJ); in my method for generating list.
index.php
<?php
include_once '../../classes/conn/connection.php';
include_once '../../classes/setups/Subdetails_setup.php';
$con = new connection();
$info = new Subdetails_setup($con);
$results = $info->getSubjectInfo();
echo $results; //this is returning a list of objects. My problem is how can i iterate these values
?>
and i tried like this echo (each($results)); but this is printing my values in a single line
like this:- Subject Name 1 FIction1Non FIction2
& My Subdetails_setup.php Class is having method getSubjectInfo() :-
function getSubjectInfo()
{
$sub_info = $this->con->prepare("SELECT * FROM subjectdetails");
$sub_info->execute();
$results = $sub_info->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $key)
{
echo $key->subject_name;
echo $key->subject_id;
}
// Return the result array
return $results;
}
Please help me for this.
-Ashutosh
This code in your Subdetails_setup.php needs to be removed, and put on the index.php. You don't need it in subdetails, just return the result.
foreach ($results as $key)
{
echo $key->subject_name;
echo $key->subject_id;
}
If you want to check if it's all working, change your index.php and add this line:
$results = $info->getSubjectInfo();
var_dump($results);
Now that var_dump() works, replace the line with the earlier code, modified to show a table:
foreach ($results as $key)
{
echo "<tr>";
echo "<td>".$key->subject_name."</td>";
echo "<td>"$key->subject_id."</td>";
echo "</tr>";
}