How to parse returned php data - php

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.

Related

How to print specific json array values in php script?

I have a json array that looks like this:
{"server-host-01":{"API":"Good","JETS":"Good","HTTPD":"Good","DISK":"23% Used","CPU":"WARNING: Avg idle at: 98% "},"server-host-02":{"DISK":"18% Used","CPU":"Avg idle at: 99% "}}
I have a key then inside that key another array of key:values and then another key with the same setup of key:values inside.
In my php script i am assigning the json file to the variable of $files and then using json_decode to turn it into a php array (i think)
$files = (my_json_file.json);
$string = file_get_contents($file);
$json_a = json_decode($string, true);
Now i have the array in php i would like to print the main keys out and then print the key:values of the keys. They will be going into a html table but specially im looking for help printing out the values as i need them before i worry about the html part.
Viewing the JSON contents
You have a JSON encoded array which contains two arrays inside of it as below (which I obtained via this link):
array (
'server-host-01' =>
array (
'API' => 'Good',
'JETS' => 'Good',
'HTTPD' => 'Good',
'DISK' => '23% Used',
'CPU' => 'WARNING: Avg idle at: 98% ',
),
'server-host-02' =>
array (
'DISK' => '18% Used',
'CPU' => 'Avg idle at: 99% ',
),
)
If you wanted to view all values pertaining to server-host-01 you could do e.g.
var_dump($json_a['server-host-01']);
If you wanted only the CPU status you could to do e.g.
$server_host_01_CPU_Status = $json_a['server-host-01']['CPU'];
var_dump($server-host-01-CPU-Status);
Example code
Here's an example of the above in action:
<?php
$json = json_decode('{"server-host-01":{"API":"Good","JETS":"Good","HTTPD":"Good","DISK":"23% Used","CPU":"WARNING: Avg idle at: 98% "},"server-host-02":{"DISK":"18% Used","CPU":"Avg idle at: 99% "}}');
$server_host_01_CPU_Status = $json['server-host-01']['CPU'];
var_dump($server_host_01_CPU_Status);
foreach($json['server-host-02'] as $key => $value)
{
var_dump("$key = $value");
}
?>
Other notes
Your line $files = (my_json_file.json); is invalid PHP. I'm not 100% sure what you're trying to achieve but firstly:
1) my_json_file.json isn't wrapped in quotes so PHP is treating it as a constant variable rather than a string (and this throws an error too -- turn PHP server errors on to see it)
2) The unquoted string my_json_file.json is wrapped in parenthesis which doesn't even do anything in this case.
Assuming what you actually want is an array of file names to then open you'd want something like this:
$files = ['my_json_file.json'];
foreach($files as $file)
{
$contents = file_get_contents($file);
$json = json_decode($contents, true);
// foreach($json as $key => $value) { ...
}
I would highly recommend checking out this tutorial for the basics on handing JSON data in PHP.

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

How to parse JSON array of objects in 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

How to change the array in order to make the desired JSON object in PHP?

I've an array titled $request as follows :
Array
(
[invite_emails] => suka#gmail.com, swat#gmail.com
[page_id] => 322
[ws_url] => http://app.knockknot.com/api/group/sendInvitation
)
After using json_encode($request) I got following output:
{
"invite_emails": "suka#gmail.com, swat#gmail.com",
"page_id": "322",
"ws_url": "http://app.knockknot.com/api/group/sendInvitation"
}
But actually I want the JSON object as follows :
{
"page_id": 322,
"invite_emails": [
"suka#gmail.com",
"swat#gmail.com"
],
"ws_url": "http://app.knockknot.com/api/group/sendInvitation"
}
How should I manipulate the array in PHP in order to get the above desired JSON object?
Please someone help me.
Split the list of emails using the comma:
$array["invite_emails"] = preg_split("#\s*,\s*#", $array["invite_emails"]);
I personally prefer using callback functions for readability and possibilities. To your purpose, array_walk should fit:
<?php
// reproducing array
$request = array(
"invite_emails" => "suka#gmail.com, swat#gmail.com",
"page_id" => 322,
"ws_url" => "http://app.knockknot.com/api/group/sendInvitation"
);
// callback finds a comma-separated string and explodes it...
array_walk($request, function (&$v,$k) {if ($k == 'invite_emails') $v = explode(", ", $v);});
// ... and then encode it to JSON
json_encode($request);
// testing
print_r($request);
OUTPUT:
{
"invite_emails":[
"suka#gmail.com",
"swat#gmail.com"
],
"page_id":322,
"ws_url":"http://app.knockknot.com/api/group/sendInvitation"
}
You are free to change the field if your needs changes, and even suppress it to be used with any field of the array.
Use PHP explode for example:
$array['invite_emails'] = explode(',',$array['invite_emails']);
To avoid spaces use preg_split (source):
$array['invite_emails'] = preg_split("/[\s,]+/", $array['invite_emails']);
This entry:
[invite_emails] => suka#gmail.com, swat#gmail.com
should be an array (currently, it is a string) in PHP, then in JSON it will look like you want it.

Php json decode with child

I been looking thru the posts here all day but can't figure out what I'm doing wrong. (I'm new to php and json)
Here is my code that work.
$json = '{"id":1234,"img":"1.jpg"}';
$data = json_decode($json, true);
echo $data["img"];
But when the json respond is this
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
it's a big harder for me. then img is a child of demo1? How to get it?
Thx. :)
Figuring out the array indices
As you're new to PHP, I'll explain how to figure out the array indces of the required array value. In PHP, there are many functions for debugging — print_r() and var_dump() are two of them. print_r() gives us a human-readable output of the supplied array, and var_dump() gives us a structured output along with the variable types and values.
In this case, print_r() should suffice:
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
$data = json_decode($json, true);
// wrap the output in <pre> tags to get a prettier output
echo '<pre>';
print_r($data);
echo '</pre>';
This will produce the following output:
Array
(
[demo1] => Array
(
[0] => Array
(
[id] => 1234
[img] => 1.jpg
)
)
[userId] => 1
)
From there, it should be pretty easy for you to figure out how to access the required vaule.
$data['demo1'][0]['img'];
Creating a helper function for ease of use
For ease of use, you can create a helper function to make this process easier. Whenever you want to view the contents of an array, you can simply call dump_array($array); and be done with it. No more messing around with <pre> tags or print_r().
Function code:
function dump_array($array) {
echo '<pre>' . print_r($array, TRUE) . '</pre>';
}
Usage example:
$arr = ['foo' => range('a','i'), 'bar' => range(1,9)];
dump_array($arr);
after decoding :
echo $data->demo[0]->img;
Basically, a { in JSON leads to a -> (it's an object).
And a [ to a [], it's an array.

Categories