Created
November 6, 2013 02:30
-
-
Save recked/7329961 to your computer and use it in GitHub Desktop.
Create a JSON file using PHP + MySQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| //http://stackoverflow.com/a/2467974 | |
| $query="SELECT * FROM tablename LIMIT 20"; | |
| $result=$mysqli->query($query) | |
| or die ($mysqli->error); | |
| //store the entire response | |
| $response = array(); | |
| //the array that will hold the titles and links | |
| $posts = array(); | |
| while($row=$result->fetch_assoc()) //mysql_fetch_array($sql) | |
| { | |
| $title=$row['title']; | |
| $url=$row['url']; | |
| //each item from the rows go in their respective vars and into the posts array | |
| $posts[] = array('title'=> $title, 'url'=> $url); | |
| } | |
| //the posts array goes into the response | |
| $response['posts'] = $posts; | |
| //creates the file | |
| $fp = fopen('results.json', 'w'); | |
| fwrite($fp, json_encode($response)); | |
| fclose($fp); | |
| /* Final Output | |
| {"posts": [ | |
| { | |
| "title":"output_from_table", | |
| "url":"output_from_table" | |
| }, | |
| ... | |
| ]} | |
| */ | |
| ?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| //http://stackoverflow.com/a/6282007 | |
| $return_arr = array(); | |
| $fetch = mysql_query("SELECT * FROM table"); | |
| while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) { | |
| $row_array['id'] = $row['id']; | |
| $row_array['col1'] = $row['col1']; | |
| $row_array['col2'] = $row['col2']; | |
| array_push($return_arr,$row_array); | |
| } | |
| echo json_encode($return_arr); | |
| /*returns a string like so: | |
| [{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}] | |
| */ | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice scripts, tried it and works like a charm. But can you please guide how to parse this json data onto HTML tag with ID or class. I tried it but got undefined.
Thx