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.
Related
I'm trying to display stored data form the mongodb using the php? But it display's all the header file including data. How to ignore the header information?
It shows like
{ "_id" : ObjectId("550ee694c5c9f2729b066c23"),
I want result as
550ee694c5c9f2729b066c23
my php code:
$db = new Mongo();
$query = $db->selectDB('test');
$collections = new MongoCollection($query,'demo');
$coursor = $collections->find();
foreach ($coursor as $doc)
{print_r($doc);}
You can find the value of the ObjectId() object as a lowercase hexadecimal string using valueOf() method.
ObjectId("550ee694c5c9f2729b066c23").valueOf() = 550ee694c5c9f2729b066c23
For more details you can check documentation :
http://docs.mongodb.org/manual/reference/method/ObjectId.valueOf/
Actually { print_r($doc); } shows header too. There should be some kind of a Key to know which data we need. So we cannot remove them.
$db = new Mongo();
$query = $db->selectDB('test');
$collections = new MongoCollection($query,'demo');
$coursor = $collections->find();
foreach ($coursor as $doc)
{
echo $doc['id'];
}
Will give you only 550ee694c5c9f2729b066c23
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'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.
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.
I'm using quercus for appengine. I tried saving a long php string (> 1000 characters) but appengine won't allow me as String can only hold 500 characters. So I tried using appengine's Text datatype. It lets me save, however, when I retrieve the data from PHP, it returns me a resource() type instead of string.
Let me explain with code:
<?php
$a = new Text("this is a long string that contains more than 1000 characters");
$b = "this is a long string that contains more than 1000 characters";
$e = new Entity('Article');
$e->setProperty('content', $a); // this works fine
// $e->setProperty('content', $b); // will complain as strlen($b) is > 500
$db = DatastoreServiceFactory::getDatastoreService();
$id = KeyFactory::keyToString($db->put($e)); // works ok, returns the ID of Entity saved
?>
Now all's fine and dandy, but when I retrieve the content of $e, it will return me a resource() type data.
<?php
$q = new Query('Article');
$ps = $db->prepare($q);
foreach($ps->asIterable() as $i) {
echo gettype($i->getProperty('content')); // this will echo Object, which when var_dump'd, gives me a resource() which is not convertible to php string, thus I can't get the human readable value
}
?>
Is there any workaround to this? Any help is GREATLY appreciated as I've been pulling my hair for days...
Ok solved it by converting java object to string
$content = $i->getProperty('content');
if(is_object($content)) {
if($content instanceof Text) {
$content = $content->getValue();
}
}