I'm trying to create a rest service for my android application where an external database returns items to be stored in the applications local database. I've got everything working except blobs are being returned as null.
this is an example of my jason response.(picture and thumbnail fields are blobs)
{"id":"2","user_id":"1","name":"testing","type":"bouldering","picture":null,"lat":"36","long":"81","alt":"41932","accuracy":"53","thumbnail":null}
Here is my php script to return the data.
<?php
require_once('config.php');
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$sql = 'select * from spot_main';
$results =$mysqli->query($sql);
$spots = array(); //array to parse jason from
while($spot = $results->fetch_assoc()){
$spots[] = $spot;
}
echo json_encode($spots);
?>
Anyone know of a solution to this problem? I know I'm not doing this the most efficient way(better to store images in the filesystem), but I need this to work.
Encode the binary data as base64 before you generate the JSON.
$obj->picture = base64_encode($binaryData);
You can then decode this in your Android application with any base 64 decoder. Since API level 8 there is a built in util class. Otherwise there are plenty of external libs you can use for targetting Android 2.1 or earlier.
you have to make BLOB to base64_encode
while($spot = $results->fetch_assoc()){
$spots[] = $spot;
}
Then prepare a foreach loop like this
foreach($spots as $key=>$value){
$newArrData[$key] = $spots[$key];
$newArrData[$key]['picture'] = base64_encode($spots[$key]['picture']);
$newArrData[$key]['thumbnail'] = base64_encode($spots[$key]['thumbnail']);
}
header('Content-type: application/json');
echo json_encode($newArrData);
It seems that json_encode works with UTF-8 encoded data only. You can use json_last_error() to detect json_encode error.
Related
I am using a plugin in my wordpress that stores my data in a specific way. I have a problem on how to extract that data into an array using php. The data currently saved in database is in this kind of format which i have never seen before. I want to get the name, price and the referral amount from this data.
I have tried using php foreach looping to extract data but it wont recognize the foreach function.
a:2:{i:0;a:4:s:4:"name";s:14:"Tower";s:2:"id";i:4177;s:5:"price";i:500;s:15:"referral_amount";s:3:"20";}i:1;a:4:s:4:"name";s:25:"Square";s:2:"id";i:3998;s:5:"price";i:178;s:15:"referral_amount";s:4:"87.4";}}
I wanted the array to store the data in this kind of way:
{
name:'Tower',
price:500,
referral_amount:20,
}
Does anyone knew how to extract this kind of data using php?
$data = 'a:2:{i:0;a:4:{s:4:"name";s:14:"Tower";s:2:"id";i:4177;s:5:"price";i:500;s:15:"referral_amount";s:3:"20";}i:1;a:4:{s:4:"name";s:25:"Square";s:2:"id";i:3998;s:5:"price";i:178;s:15:"referral_amount";s:4:"87.4";}}';
$data = preg_replace_callback('!s:(\d+):"(.*?)";!',
function ($match) {
return 's:'.strlen($match[2]).':"'.$match[2].'";';
},
$data);
$data_array = unserialize($data);
$final_data = json_encode($data_array);
echo $final_data;
I have successfully stored an image into a MongoDB database, since it is stored as a Base64 type information; I want to retrieve that BinData to a string. How do I do that? Here I am finding my document using input 'Email'.
<?php
$m = new MongoClient();
$db = $m->mydb2->mycol2;
$result = $db->find(array('Email'=>$em));
foreach( $result as $key){
$susername = $key['Email'];
$imagebody = $key['pic'];
}
echo $imagebody;
?>
EDIT:
As Haresh has said
$imagebody = $key['pic']->bin
works perfectly. But it returns me something like Raw data but if I write this
$imagebody = base64_encode($key['pic']->bin);
then it returns me exact Base64 format.
According to Documentation
To access the contents of a MongoBinData, use the bin field which return the string Mongo Binary Data
So Try this:
$imagebody = $key['pic']->bin
Hope this works for you.
I am saving my images directly in the database (Yes I have read about that and know it's better to save the path to the image).
The problem is selecting the image field which is a blob returns NULLto my JSON. I have alot read quite a few stackoverflow links of the same query but still not a clear explanation/ answer received has been able to help me.
I have encoded using base_64 but when doing so nothing is showed on the webpage.
Would appreciate if I could be pointed in the correct direction.
This is part of my code:
header("Content-Type:application/json");
//select query
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
if (!empty($rows))
{
$encode = array("StudentsList" => $rows);
//$json_response=json_encode($encode);
$json_response=base64_encode($encode);
echo $json_response;
echo json_last_error(); //Returns 0
}
if you need the json data
please use json_encode
example
echo json_encode($json_response);
and also read php manual
http://php.net/manual/en/function.json-encode.php
I am trying to get JSON response using PHP. I want to have Json array not the HTML tags. But the output shows HTML tags as well.I want to remove this HTML output! PHP code is as follows: I don't know how to do this ? Please help.
Thanks in advance :)
<?php
function getFixture(){
$db = new DbConnect();
// array for json response of full fixture
$response = array();
$response["fixture"] = array();
$result = mysql_query("SELECT * FROM fixture"); // Select all rows from fixture table
while($row = mysql_fetch_array($result)){
$tmp = array(); // temporary array to create single match information
$tmp["matchId"] = $row["matchId"];
$tmp["teamA"] = $row["teamA"];
$tmp["teamB"] = $row["teamB"];
array_push($response["fixture"], $tmp);
}
header('Content-Type: application/json');
echo json_encode($response);
}
getFixture();
?>
It's difficult to tell without seeing what your output is, but there is nothing in your code which would add HTML to your response.
It sounds like the HTML is in the database, so you're getting the data as expected, and your browser is the displaying whatever html elements might be there.
You could ensure none of the rows from the database have HTML in them by using strip_tags as follows:
$tmp["teamA"] = strip_tags($row["teamA"]);
Do this for all rows which may contain html.
Sorry if this is not formatted right, I'm new to StackOverflow!
http://php.net/strip-tags
I just wanted some input about my use of JSON.
<?php
header('Content-Type: text/plain');
//results
$results = array();
for($i=0;$i<20;$i++)
{
$result = array();
$result['name'] = 'Test Season '.ceil(($i+1)/13).' Episode '.(($i%13)+1);
//$result['torrent'] = 'https://www.example.com/?id='.$i.'&key='.uniqid();
$result['torrents'] = array();
$c = mt_rand(1,4);
for($j=0;$j<$c;$j++)
{
$torrent = array();
$torrent['url'] = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent['codec'] = $j%2 == 0 ? 'xvid' : 'h264';
$torrent['resolution'] = '720p';
$result['torrents'][] = $torrent;
}
$results[] = $result; //push
}
echo json_encode($results);
?>
This is just some test code, not an actual implementation. Am I using JSON correctly and too the fullest? Or is some better method of doing this?
I have legal torrents that I'd like to do some JSON with.
Torrents are grouped by name which contain multiple torrents (actual links to data). And other information such as codec etc.
This is my first time actually outputting JSON, would XML be better?
Are there any guides on this topic (hopefully not entire books)?
Thanks.
What you doing is right. I like to use the StdClass to make objects rather than key value arrays, just cause it looks sexier! E.g.
$torrent = new StdClass();
$torrent->url = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent->codec = $j%2 == 0 ? 'xvid' : 'h264';
$torrent->resolution = '720p';
$result['torrents'][] = $torrent;
As you say you don't need to read a whole book on the matter, I would have a look here http://php.net/manual/en/book.json.php to get to grips with the basics of JSON.
In terms of JSON vs XML, I find it far easier to represent data as JSON as it is easier to fetch the specific data you want much in the same way you can access the info in a stdClass object.
[EDIT]
And as Stefan Gehrig says make sure you define your content type as "application/json".
Absolutely fine. You could only change the MIME type to be RFC 4627 compliant though: application/json.