Is it possible to use two json_encode() in one php file? - php

I'm trying to use json to send text and blob image information from MySQL to iPhone App.
However, someone told me that I should separate text and blob image info because blob is technically not binary - thus I have to use base64_encode(). Well.... I'm going to create two php files but want to check if it's possible to do it in one php file. :/ I tried but n o luck yet... Is it even possible?

You can invoke json_encode, the function, as often as you want.
But throwing the output together is not going to work.
If you intended to do
print json_encode($data_array);
print json_encode($image_blob);
Then this will lead to an invalid JSON response.
Like {"data":123} {"image":"PNG%...."}
You need to combine the data and the image blob somehow if you want this to work in one response:
print json_encode(array_merge($data_ar, array("image"=>$image_blob)));

Yes, you just need to have some kind of conditional to decide which JSON document you are going to return… but if you are going to serve the image up separately then you are almost certainly better off just serving up the image and not encoding it in a JSON document.

There is no such restriction. You can use json_encode as many times as you need.

Related

Using data from a web-service in an iOS Application

I have to list the table entries from mysql in my iPhone app when a button is pressed. I am able to do it properly but it is just not the way I want it. I am using a PHP script to send Xcode what has to be printed.
First, I tried doing it using HTML table, but I didn't like the way it was printed with cells. Next I tried printing plain text by giving spaces(between columns) and \n for every new row. I used NSURL and loaded the webView to the iPhone. Looks good on browser but the same is not preserved when the iPhone tries to open it.
Is there a good way to do this? So I can just list the table entries without having to go through the traditional HTML table or any other idea is welcome.
Also, please try to be easily understood, as I am new to Obj-C, and PHP as well.
Thanks!!
Any thoughts on how I can do this in a UITableView..?? Do I have to return a string with component separation characters and fill in the tableView?
Output the results encoded in JSON. Send an a(sync) request to the server using NSURLConnection or using a third-party library such as AFNetworking. Parse the JSON using NSJSONSerialization, turning the results into an array/dictionary depending on the contents. Then parse the results into the UITableViewCell. It may be easier to subclass the cell so that you include the data that you'd like to use.
To encode the results from the database into JSON, you can use the method json_encode().

Is there a way to query JSON in PHP?

I've used Google, Yahoo, AND Bing, but I can't find any good answers. I've seen jLinq, but I want to be able to query JSON in PHP in hopes of having a not an SQL database, but instead all data storage within the filesystem on my server. No, I don't care how bad it sounds.
Ideas nonetheless? I would think that there would be a PHP class on this.
-----EDIT-----
Guys, thanks for your answers so far, but I don't think that json_encode and json_decode are of much use. What I want to be able to do is encode/decode JSON, and be able to search it for specific keys with specific values. Albeit I have PROVEN to myself that I can do so, it's a lot of code for something that should be so simple. Anything else you have in mind?
You can use JsonQ package. This package can query over JSON data like Query Builder.
https://github.com/nahid/jsonq
You can call json_encode to convert your data to a string, and write this string to a file. Then when you want to use it, you read the entire file and call json_decode to convert it back to data. When you're done processing it, repeat the encode/write steps.
But if you have multiple processes doing this, they'll completely overwrite what each other is doing. So it's not a very good way to manage shared data.
You could try JSONPath it allows you to query json with xpath as you would xml.
Look into json_decode. This lets you take JSON as a string and parse it into an object in PHP. You could theoretically store the strings as files, and use file_get_contents to retrieve the string from the file.
You would have to write your own searching/indexing/updating/etc algorithms, but if you don't want to use a real database solution (since you said, No, I don't care how bad it sounds.), then I guess this would work.
To search for values in the object you get from json_decode, look into in_array and array_search

PHP encdoe function for file name

I'm learning about the function urlencode. Is it possible to use this on a file name? So - when you upload a file to your server and then use that file name later, you would be able to use it in a url?
$promotionpicture=$_FILES["promotionpicture"]["name"];
$promotionpicture=rawurlencode($promotionpicture);
Then later...
$imagesource="http://mysite.com/".$userID."/".$promotionpicture;
I'm trying to do this, but every time I navigate to the picture, i get a "Bad request" from my server. Is there a specific php encode function I should use? Or is this wrong all together? Thanks in advance for you help.
urlencode and similar functions are for making an HTTP friendly URL. You would want to keep the normal filename and then when printing the img src, use urlencode.
Note that this is not really the preferred way to do it as you can run into duplicate filenames and misc security issues. It's better to generate a filename for it using a uuid or timestamp or something, that way you can bypass those types of issues.
Pictures are really just raw data, like any other file. It is possible to do something like what you're doing, but not necessarily advisable.
If you want to do something like that, I recommend instead doing something to strip special characters.
$newfilename=preg_replace('/[^a-zA-Z0-9.]/','',$filename);
(from Regex to match all characters except letters and numbers)
That said, keep in mind what others have said. How will you handle file name collisions? Where will the images be stored and how?
One easy way to do this much more robustly is to store in a database the original file name and the MD5 hash. Save the file by its hash instead of by name, and write a script that retrieves the file by matching the original name to the MD5 using the database. If you store the file type, you can issue correct headers and when the user downloads the file or uses it to embed in a web page, it will retain its original name, or display as expected respectively.

JQ-GRID implementation in php file

Hi friends i am working on JQ-GRID. I want to show Image in specific column, But i don't know how to attach image in JQ-GRID. Can anybody help me or please send me some links, thanks
jqgrid is a feature monster. I tell this everybody who asks about it.
When jqgrid loads, a function is called which actually gets the data you want to display.
This is normally an ajax call to your php. As a result set of this function, you can just use xml or json.
I prefer json, so I build my result array and do a echo json_encode($myarray)
jQuery("#your_grid_id").jqGrid({ url : '/ajax/getjqgriddata.php'})
Now displaying pictures, there are different ways you can do that. You can either generate a <img src="wherever/mypicture1.png"></img>-link and hand it over in your result, or encode your picture binary data with base64 and deliver it with your result.
A more addvanced way is to use an so called formatter and just returning a id for the image.
This depends on you, but I would suggest to get confident with jqgrid, experiment with returning -links to get a feeling how jqgrid works.
There is plenty of good documentation at:
http://trirand.com/blog/jqgrid/jqgrid.html
Just take a look at it.

Why need to use JSON in php and AJAX

I just started doing jQuery last week, and so far I already made some basic systems with ajax, like basic jQuery CRUD and simple chat system without referencing on other's work for I decided to test myself on how far I can do systems alone in jQuery(without JSON and XML yet).
But when I decided to look at other's work (hoping to get/learn good practices and codes out there) many or almost every program that deals with ajax have some JSON in it. So I decided to study and read JSON specially this one, but I guess because it's my first time dealing with it, I'm having a problem sinking it into my brain. Yeah I know it is a "lightweight way of describing hierarchical data", I also know how to make JSON like mixing a literal array and object in JS, and how to dsplay it in js.
But my question is, what's the difference and what's the advantage than not using it?
When I can still get and store data on the server using ajax and database without JSON.
By the way I haven't focus on XML yet because based from my research it's better to use JSON in AJAX.
Can you give me some actual scenario dealing with
s1. ajax php mysql (this with what disadvantages?)
and
s2. ajax php mysql json (this with what advantages?)
I mean, my focus is to send and get data, and I already can do it with s1.
Sorry if you find my question stupid. Tia. :)
Why use JSON? The answer is portability and structure.
JSON is portable because parsers and writers are available for many, many languages. This means that JSON that a PHP script generates can be very easily understood by a JavaScript script. It is the best way to transmit complex structures like arrays and objects, and have it still be compatible with multiple languages.
JSON provides structure because the data you transmit with it can have consistent formatting. This is instead of transmitting back plain-text (i.e. unformatted) data, like comma-separated or delimited data.
Data that is merely delimited (for example, "BookName1,BookName2,BookName3") is more difficult for humans to understand, debug, and work with. If you wanted to debug a response between your server and your browser and the data was delimited (like my example above), you might have a hard time understanding it. Also, if you want to add different data types, provide separate records, etc., then your custom data format becomes more complicated. Eventually, you might end up reinventing JSON.
As a side note, JSON is indeed better than XML. It is much more efficient space-wise. There are no tag names to take up space. Structure is created via nested braces, instead of verbose tags.
Resources
Here is an interesting article on the differences and pros/cons of XML and JSON: http://www.json.org/xml.html
Examples
Per your request, here is an example of encoding JSON with PHP. This is ripped from the docs:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
Output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Contrast this to something like this, without JSON:
a,1
b,2
c,3
d,4
e,5
To parse that, you'd have to iterate through each line, split the values yourself, and then create the array. This isn't that difficult, but imagine you have a nested object:
$arr = array ('a'=> array(1,2,3),'b'=> array('a' => 1, 'b' => 2),'c'=>3,'d'=> array(1,2,3,4,5) ,'e'=>5); // etc.
With JSON, it's no different to encode it. Just use json_encode. But, encoding this manually, and then decoding it manually would be significantly more work.
Programming in any sort of programming language, you have several different types of data at your disposal, including the very useful array type.
Interchanging data between Javascript and any server side language can only happen through strings. I.e. you can send and return any text, but there's no way to send a native array or number type.
JSON is an elegant way to express array and other types using only a string. This way you can pass arbitrary data back and forth between different environments and are not limited to pure text. XML solves the same kind of problem, but is often overkill for simple AJAX requests.

Categories