How to parse JSON array of objects in PHP - php

I am new to php programming. Here in my project I am trying to parse JSON data coming from php web service. Here is the code in web service.
$query = "select * from tableA where ID = 1";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$arr= array();
while ($row = mysql_fetch_assoc($result)) {
$arr['articles'][] = $row;
}
header('Content-type: application/json');
echo json_encode($arr);
}
else{
echo "No Names";
}
This is giving me data in this JSON format.
{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}
Now here is my php page code.
<?php
$jfile = file_get_contents('http://localhost/api/get_content.php');
$final_res = json_decode($jfile, true) ;
var_dump( $final_res );
$content = $final_res->articles->Content;
?>
I want to show the content on webpage.
I know code at var_dump( $final_res ); is working. But after that code is wrong. I tried to look at many tutorials to find the solution but didn't find anyone. I don't know where I am wrong.

The second parameter of json_decode determines whether to return the result as an array instead of an object. Since you set it to true your result is an array and not an object.
$content = $final_res['articles'][0]['Content'];

As an alternative answer, if you want to use it as an object, use this code:
$a = '{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}';
$final_res = json_decode($a);
echo '<pre>';
print_r($final_res);
echo '</pre><br>';
Note that I removed the second part (true) from the json_decode
Output:
stdClass Object
(
[articles] => Array
(
[0] => stdClass Object
(
[ID] => 1
[Title] => Welcome
[Content] => This is the first article.
)
)
)
Accessing Content:
echo 'Content: ' . $final_res->articles[0]->Content;
Output:
Content: This is the first article.
Run code

Related

Convert MySQL to Json ResultSet

I'm trying to turn my results into a json encoded string. I know that now working on an external api seems a bit much, but I do think that it's something that will come in handy as times goes on. Currently, I use the following function:
//API Details
public function APIReturnMembers() {
$query = <<<SQL
SELECT uname
FROM {$this->tprefix}accounts
SQL;
$encode = array();
$resource = $this->db->db->prepare( $query );
$resource->execute();
foreach($resource as $row) {
$encode[] = $row;
}
echo json_encode($encode);
}
It does what it's supposed to as far as returning results go, e.g.:
[{"uname" : "guildemporium"}, {"uname" : "doxramos"}]
When I saw that I was ecstatic! I was on my way to implementing my own API that others could use later on as I actually got somewhere! Now of course I have hit a hickup. Testing my API.
To run the code to get the results I used
$api_member_roster = "https://guildemporium.net/api.php?query=members";
$file_contents = #file_get_contents($api_member_roster); // omit warnings
$memberRoster = json_decode($file_contents, true);
print_r($memberRoster);
The good news!
It works. I get a result back, yay!
Now the Bad.
My Result is
[
0 => ['uname' => 'guildemporium'],
1 => ['uname' => 'doxramos']
]
So I've got this nice little number integer interrupting my return so that I can't use my original idea
foreach($memberRoster as $member) {
echo $member->uname;
}
Where did this extra number come from? Has it come in to ruin my life or am I messing up with my first time playing with the idea of returning results to another member? Find out next time on the X-Files. Or if you already know the answer that'd be great too!
The numbered rows in the array as the array indices of the result set. If you use print_r($encode);exit; right before you use echo json_encode($encode); in your script, you should see the exact same output.
When you create a PHP array, by default all indices are numbered indexes starting from zero and incrementing. You can have mixed array indices of numbers and letters, although is it better (mostly for your own sanity) if you stick to using only numbered indices or natural case English indices, where you would use an array like you would an object, eg.
$arr = [
'foo' => 'bar',
'bar' => 'foo'
];
print_r($arr);
/*Array
(
[foo] => bar
[bar] => foo
)*/
$arr = [
'foo','bar'
];
/*Array
(
[0] => foo
[1] => bar
)*/
Notice the difference in output? As for your last question; no. This is normal and expected behaviour. Consumers will iterate over the array, most likely using foreach in PHP, or for (x in y) in other languages.
What you're doing is:
$arr = [
['abc','123']
];
Which gives you:
Array
(
[0] => Array
(
[0] => abc
[1] => 123
)
)
In order to use $member->foo($bar); you need to unserialize the json objects.
In you api itself, you can return the response in json object
In your api.php
function Execute($data){
// Db Connectivity
// query
$result = mysqli_query($db, $query);
if( mysqli_num_rows($result) > 0 ){
$response = ProcessDbData($result);
}else{
$response = array();
}
mysqli_free_result($result);
return $response;
}
function ProcessDbData($obj){
$result = array();
if(!empty($obj)){
while($row = mysqli_fetch_assoc($obj)){
$result[] = $row;
}
return $result;
}
return $result;
}
function Convert2Json($obj){
if(is_array($obj)){
return json_encode($obj);
}
return $obj;
}
Calling api.php
$result = $this->ExecuteCurl('api.php?query=members');
print_r($result);
here you $result will contain the json object

I want array in its original form

I created an array using PHP and Microsoft office access database using this code
Code:
<?php try{
$sql = "SELECT * FROM mcc ";
$result = $conn->query($sql);
$row = $result->fetchAll(PDO::FETCH_ASSOC);
print_r($row);
}catch(PDOExepction $e){
echo $e;
}?>
Output:
Array ( [0] => Array ( [sName] => Dihn [Name] => John Parker [BNE] => BOB DIHN ) )
Now I want to use this array for further operation like make an excel file and all but i cant because array contains []"Square brackets" ,"String without double quotation " ,"string with space" and no ","(comma) between two rows.
how can i simplify this code to use like normal array or any other suggestion.please help me
$row is an array (as PHP tells you in the output of print_r), so the array exists. print_r just outputs a more human-readable form of the array, that's exactly what the function was designed for. If you don't want that, then you are using the wrong function.
If you want to process the array using PHP, don't echo it, but use it directly, e.g. like this:
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
// Rows is an array of the results
foreach($rows as $row) {
$thename = $row['Name'];
// Do something with the data
}
If you want to output the array in valid PHP syntax, the easiest solution is to replace print_r with var_export:
$row = $result->fetchAll(PDO::FETCH_ASSOC);
var_export($row);
You did not give the slightest hint about how you want to process the output. However, if you want to process the output of your script, it might be easier to use JSON:
echo json_encode($row);

json decode/encode repeated array

hey ive managed to decode the encode json i created but when i try to print the decoded array it repeats the same username ( the last one on the list ) over and over again. what i want is that all the users are desplayed
this is the code for the encoded json array
$query =
"SELECT
userid,
username,
password,
email
FROM Users ORDER BY userid";
$results = mysqli_query($connection,$query);
The encoded array code below
<?php
echo "Data with Json Encoding";
foreach($results as $row){
$encode = json_encode($row, true);
echo '<pre>';print_r($encode); echo '</pre>';
}
?>
the decoded array code below
<?php
echo "Data with Json Decoding";
foreach($results as $row){
$decode = json_decode($encode, true);
echo '<pre>'; print_r($decode);'</pre>';
}
this is the result of the code Data with Json Decoding
Array
(
[userid] => 239
[username] => desposit4221
[password] => 699e5fae54df4c82314e42dd86c4d383
[email] => ad471993#hotmail.com
)
Array
(
[userid] => 239
[username] => desposit4221
[password] => 699e5fae54df4c82314e42dd86c4d383
[email] => ad471993#hotmail.com
)
it's this over and over again, it should be the list of my users
any help would be greatly appreciated
echo "Data with Json Encoding";
$encodedResults = array();
foreach($results as $row){
$encode = json_encode($row, true);
echo '<pre>';print_r($encode); echo '</pre>';
$encodedResults[] = $encode;
}
?>
echo "Data with Json Decoding";
foreach($encodedResults as $row){
$decode = json_decode($row, true);
echo '<pre>'; print_r($decode);'</pre>';
}
If you put the line
$encode = json_encode($row, true);
into your second loop just after the foreach line, you should get the results you expect. It's a reasonable way to explore the datamanagement aspects of php. Good luck in your projects!
Encode your array:
echo "Data with Json Encoding";
$encoded_datas = json_encode($results);
echo $encoded_datas;
Decode the string into an array:
echo "Data with Json Decoding";
$decoded_datas = json_decode($encoded_datas, true);
echo '<pre>';
print_r($decoded_datas);
echo '</pre>';
You don't need to encode (and then decode) your array row by row.
Plus, as explained in comments and as shown in costa's answer, your code didn't work because you were decoding the same string each time: your $encoded variable contains the last value you put in it (the last row you encoded).

Display JSON format data

When a retrieve the according data from the database then encode it as json then pass it to the view:
$json_data = json_encode($x);
$search_results['search_results'] = $json_data;
$this->load->view('findquestions',$search_results);
If I display this in the view we get:
[{"question_title":"java"},{"question_title":"big java book"}]
How can the question_titles so "java" be extracted and presented as a url link or inside a table
Since you're passing the json-string directly to the view and then process it (for display) through PHP, you should be able to use PHP's json_decode() to convert it into an object (or array) to use it in a more-friendly manner:
// use json_decode with `true` to get an associative array
$results = json_decode($search_results['search_results'], true);
You can now access the data either directly or within a loop:
// direct access
$title1 = $results[0]['question_title'];
// in a loop
foreach ($results as $result) {
echo 'Title: ' . $result['question_title'];
}
For reference, using the sample-data supplied in the question, a print_r() of the data:
print_r($results);
Array (
[0] => Array (
[question_title] => java
)
[1] => Array (
[question_title] => big java book
)
)
To process the results in PHP
In your controller:
$search_results['search_results'] = $x; //store the array
$this->load->view('findquestions',$search_results); //pass the results as PHP array to view
In your view:
foreach($search_results as $result){
echo $result['question_title'];
}

How to parse returned php data

I am accessing an external PHP server feed (not a real link):
$raw = file_get_contents('http://www.domain.com/getResults.php');
that returns data in the following context:
<pre>Array
(
[RequestResult] => Array
(
[Response] => Success
[Value] => 100
[Name] => Abracadabra
)
)
</pre>
But I can't figure out how to handle this response... I would like to be able to grab the [Value] value and the [Name] value but my PHP skills are pretty weak... Additionally if there is a way to handle this with JavaScript (I'm a little better with JavaScript) then I could consider building my routine as a client side function...
Can anyone suggest a way to handle this feed response?
How about something like this
function responseToArray($raw)
{
$result = array();
foreach(explode("\n", $raw) as $line)
{
$line = trim($line);
if(stripos($line, " => ") === false)
{
continue;
}
$toks = explode(' => ', $line);
$k = str_replace(array('[',']'), "", $toks[0]);
$result[$k] = $toks[1];
}
return $result;
}
does $raw[RequestResult][Value] not work? I think the data is just a nested hash table
The script on the other side can return a JSON string of the array, and your client script can easily read it. See json_encode() and json_decode(). http://www.php.net/json-encode and http://www.php.net/json-decode
What you are doing on the "server" script is actually to var_dump the variable. var_dump is actually used more for debugging to see what a variable actually contains, not for data transfer.
On server script:
<?php
header("Content-Type: application/json");
$arr_to_output = array();
// .. fill up array
echo json_encode($arr_to_output);
?>
The output of the script would be something like ['element1', 'element2'].
On client script:
<?php
$raw = file_get_contents('http://example.com/getData.php');
$arr = json_decode($raw, true); // true to make sure it returns array. else it will return object.
?>
Alternative
If the structure of the data is fixed this way, then you can try to do it dirty using regular expressions.
On client script:
<?php
$raw = file_get_contents('http://example.com/getData.php');
$arr = array('RequestResult'=>array());
preg_match('`\[Response\]\s\=\>\s([^\r\n]+)`is',$raw,$m);
$arr['RequestResult']['Response'] = $m[1];
preg_match('`\[Value\]\s\=\>\s([^\r\n]+)`is',$raw,$m);
$arr['RequestResult']['Value'] = $m[1];
preg_match('`\[Name\]\s\=\>\s([^\r\n]+)`is',$raw,$m);
$arr['RequestResult']['Name'] = $m[1];
// $arr is populated as the same structure as the one in the output.
?>
Two possible solutions:
Solution #1 Change one line at the source:
It looks like getResults.php is doing a print_r. If that print_r could be changed to var_export you would get a PHP-parseable string to feed to eval:
$raw = file_get_contents('http://www.domain.com/getResults.php');
$a= eval($raw);
echo($raw['RequestResult']['Value']);
Be warned, eval'ing raw data from an external source (then echo()'ing it out) is not very secure
Solution #2 Parse with a regex:
<?php
$s= <<<EOS
<pre>Array
(
[RequestResult] => Array
(
[Response] => Success
[Value] => 100
[Name] => Abracadabra
)
)
</pre>
EOS;
if (preg_match_all('/\[(\w+)\]\s+=>\s+(.+)/', $s, $m)) {
print_r(array_combine($m[1], $m[2]));
}
?>
And now $a would contain: $a['Value']==100 and $a['Name']=='Abracadabra' etc.

Categories