JSON url field is not correctly displaying - php

So this is where to view my json file: http://alyssayango.x10.mx/
this is my php file for that:
<?php
include('connectdb.php');
$sql = "SELECT * FROM tblmovies ORDER BY _id";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$set = array();
while($row1 = mysql_fetch_assoc($result)) {
$set[] = $row1;
}
echo json_encode($set);
and the output is:
[{"_id":"3","movie_name":"Despicable Me 2","movie_cinema_number":"CINEMA 1","movie_length":"1hr. 40mins.","movie_type":"GP","movie_schedules":"12:10 PM | 02:25 PM | 04:40 PM","movie_image_url":"http:\/\/i39.tinypic.com\/szizo4.jpg"},{"_id":"4","movie_name":"White House Down","movie_cinema_number":"CINEMA 2","movie_length":"2 hrs. 10 mins.","movie_type":"PG-13","movie_schedules":"12:30 PM | 03:20 PM | 06:10 PM","movie_image_url":"http:\/\/i39.tinypic.com\/vp9n9j.jpg"},{"_id":"5","movie_name":"My Lady Boss","movie_cinema_number":"CINEMA 3","movie_length":"1hr. 50 mins.","movie_type":"PG-13","movie_schedules":"01:00 PM | 03:30 PM | 06:00 PM","movie_image_url":"http:\/\/i44.tinypic.com\/2qlv08z.jpg"},{"_id":"6","movie_name":"Four Sisters And A Wedding","movie_cinema_number":"CINEMA 4","movie_length":"2 hrs. 5 mins. ","movie_type":"PG-13","movie_schedules":"12:30 PM | 03:10 PM | 05:50 PM","movie_image_url":"http:\/\/i44.tinypic.com\/9iv0d1.jpg"}]
what seems to be wrong that I do in here? URL is displayed as: http:\ /\ /i44.tinypic.com\ /9iv0d1.jpg where it should be http://i44.tinypic.com/9iv0d1.jpg

The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.
If you create an API that should be:
$array = array("title" => "TEST", "username" => "test"); // Creating a array
echo json_encode($array); // Printing json
Client want to request and get response:
$json = file_get_contents('http://www.example.com/test/films.json'); // Your url
$array = json_decode($json); // Your first array its here!
More: http://en.wikipedia.org/wiki/JSON
Warning: You can't edit or tidy your json response! It is good!

The problem does not exists, actually.
What you're doing wrong is that you're using a piece of your JSON string without decoding it beforehand. Just use json_decode(..) if you're within PHP or the equivalent javascript function to decode JSON.
Once you did that, you'll have an object / an array which contains the data in the correct form.

Related

Changing json format in php

I have a json output from a database quesry that looks as follows:
[
{
"name": 1,
"value": "27.18161362"
},
{
"name": 2,
"value": "323.69645128"
},
{
"name": 3,
"value": "23.16249181"
}
]
I am trying to plug this into a script that will make charts from the data. The script requires the data to be in the following format:
{"script":
[
{"name":"1","value":27.18161362},
{"name":"2","value":323.69645128},
{"name":"3","value":23.16249181}
]
}
If it is not formatted in this way, the script claims that it is not valid json and contains no valud json head.
The output does use a valid json content header but that appears not to be enough for the script I am using.
So the question is, how can I convert the json output from a database call shown in first example, into the format the script is looking for show in the second example.
Code that creates json is fairly standard:
$stmt = $db3->prepare("SELECT week AS name, SUM(he.earnings) AS value FROM hotspot_earnings he INNER JOIN emrit_hotspots eh ON eh.hotspot_name = he.hotspot_name WHERE year = '2020' GROUP BY year, week");
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json; charset=UTF-8');
echo json_encode($row, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$stmt = $db3->prepare("SELECT week AS name, SUM(he.earnings) AS value FROM hotspot_earnings he INNER JOIN emrit_hotspots eh ON eh.hotspot_name = he.hotspot_name WHERE year = '2020' GROUP BY year, week");
$stmt->execute();
// Change here
$row = ['script' => $stmt->fetchAll(PDO::FETCH_ASSOC)];
Not sure if you can edit the initial json output with php. If it's called by AJAX and you can control the php file you can try something like this. Just build the new array.
$new_array = array('script' => $row);
echo json_encode($new_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Mailgun Webhook to track event: how to pass output to database

I am using a Mailgun Webhook to track events (delivered, opened, etc). I successfully redirected the event to a url that has a php file that looks like this:
<?php
$postdata = file_get_contents("php://input");
$postdata_encoded = json_encode($_POST['message-headers']);
When I echo the output I am getting the following:
[[\"Received\", \"by luna.mailgun.net with SMTP mgrt 8734663311733; Fri, 03 May 2013 18:26:27 +0000\"], [\"Content-Type\", [\"multipart/alternative\", {\"boundary\": \"eb663d73ae0a4d6c9153cc0aec8b7520\"}]], [\"Mime-Version\", \"1.0\"], [\"Subject\", \"Test deliver webhook\"], [\"From\", \"Bob \"], [\"To\", \"Alice \"], [\"Message-Id\", \"<20130503182626.18666.16540#mail.example.com>\"], [\"X-Mailgun-Variables\", \"{\\"my_var_1\\": \\"Mailgun Variable #1\\", \\"my-var-2\\": \\"awesome\\"}\"], [\"Date\", \"Fri, 03 May 2013 18:26:27 +0000\"], [\"Sender\", \"bob#mail.example.com\"]]
Question: How can I transform this output to a proper json format that I will be able to pass to my database? I tried something like this:
$output = array();
foreach ($postdata_encoded as $key=>$value) {
$output[$key] = $value;
}
var_dump($output);
but this returns:
Response: array(0) { }
Any idea? Many thanks

How to lookup data in a json file using php

Using PHP, I'm looking to get an id passed via the url and then lookup some data in a JSON file... then display the data back on the page.
I'll set up the url to be http://mytestapp.php?id=12345678 and then use;
$id = $_GET['id'];
to set the id variable. I then have a JSON as below;
{
"ads":
[
{ "id":"12345678",
"hirername":"Test Hirer",
"hirercontact":"Rob A",
"role":"Ultra Sat Role",
"requirements": [
{"req":"Right to work in Australia"},
{"req":"Live locally"}],
"candidates": [
{"name":"John Smith","dist":"Nunawading (23km away)","exp1":"Pizza maker at Don Domenicos for 4 years","exp2":"Bakery Assistant at Woolworths for 4 years","req":"","avail1":"Mon to Fri | Morning, Evening & Night","avail2":"","call":"0413451007"},
{"name":"Jack Smith","dist":"Endeadvour Hills (35km away)","exp1":"Pizzaiolo (Pizza maker) at Cuor Di Pizza for 1 year","exp2":"","req":"","avail1":"Mon to Fri | Morning & Evening","avail2":"","call":"041345690"}]
},
{ "id":"12345679",
"hirername":"Test Hirer 2",
"hirercontact":"Jesse S",
"role":"Ultra Sat Role 2",
"requirements": [
{"req":"Right to work in Australia"},
{"req":"Live locally"}],
"candidates": [
{"name":"Jill Smith","dist":"Nunawading (23km away)","exp1":"Pizza maker at Don Domenicos for 4 years","exp2":"Bakery Assistant at Woolworths for 4 years","req":"","avail1":"Mon to Fri | Morning, Evening & Night","avail2":"","call":"0413451007"},
{"name":"Jenny Smith","dist":"Endeadvour Hills (35km away)","exp1":"Pizzaiolo (Pizza maker) at Cuor Di Pizza for 1 year","exp2":"","req":"","avail1":"Mon to Fri | Morning & Evening","avail2":"","call":"041345690"}]
}
]
}
Which i want to search for the id, and then be able to echo the contents of the data out.
I'm reading the JSON and decoding into an array as such;
$json = file_get_contents('data.json');
$arr = json_decode($json, true);
But i'm not sure how to now read the array, find the data i want based on the id, and then pull out the data so i can display it on the page as follows;
Hirer: Test Hirer
Contact: Rob A
Role: Ultra Sat Role
Requirements:
- Right to work in Australia
- Live Locally
John Smith Nunawading (23km away)
Pizza maker at Don Domenicos for 4 years
Bakery Assistant at Woolworths for 4 years
Mon to Fri | Morning, Evening & Night
0413451007
Jack Smith Endeadvour Hills (35km away)
Pizzaiolo (Pizza maker) at Cuor Di Pizza for 1 year
Mon to Fri | Morning & Evening
041345690
Any ideas?
Thanks Rob.
Borrowed the example from #RobbieAverill and modified to suit your needs, please check if this works.
<?php
$id = $_GET['id'];
$json = file_get_contents('data.json');
$foundAd = null;
$json = json_decode($json,true);
foreach ($json['ads'] as $ad) {
if ($ad['id'] == $id) {
$foundAd = $ad;
break;
}
}
echo "Hirer:".$foundAd['hirername']."<br/>";
echo "contact:".$foundAd['hirercontact']."<br/>";
echo "role:".$foundAd['role']."<br/><br/>";
echo "Requirements<br/>";
echo "<ul>";
foreach($foundAd['requirements'] as $req){
echo "<li>".$req['req']."</li>";
}
echo "</ul><br/>";
foreach($foundAd['candidates'] as $req){
echo $req['name']." ". $req['dist']."</br>";
echo $req['exp1']."</br>";
echo $req['exp1']."</br>";
echo $req['avail1']."</br>";
if($req['avail2']!=""){
echo $req['avail2']."</br>";;
}
echo $req['call']."</br></br>";
}
?>
In your current inplementation you need to loop over all the ads objects like
foreach ($arr['ads'] as $ad){
if ($ad['id'] == $id){
//do stuff;
}
}
A better implementation would be to use the value of the id as the key of the json object when you store the json. Using something like
$ads[id] = $yourjsonobject;
Then referencing would just be $arr['ads'][id];.
You can then use multiple foreach or if your keys are knows just use the keys to output the object you need like
echo $ad["hirername"];
Using the foreach loop to print the complete object:
foreach( $ad as $value){
print_r($value);
}

JSON - PHP foreach persistant error

Am quite frustrated with this and could use some savvy minds.
Am building a relatively simple API.
Using PHP have created the stdClass()'s and json_encode.
On the host server the data echos perfectly.
On the client side am getting a persistent foreach invalid argument error.
$thefez= new stdClass();
$thefez->muid=$id;
$thefez->bandname=$bandname;
$thefez->core=new stdClass();
$thefez->core->joined=$since;
$thefez->core->bandbio=$bio;
$thefez->core->genre=$genre;
$thefez->core->subgenre=$subgenre;
echo json_encode($thefez);
The Result (Host)
{"muid":"IM5LGM02MFS8RJLKGY9W","bandname":"Marbles For Zen","core":
{"joined":"Sun 01 March 2015","bandbio":"Zen And Marbles","genre":"Rhythm Blues",
"subgenre":"Dixie Rhythm"}}
{"muid":"IMA3YNBKZQDNR9RBCSRI","bandname":"Frankie Storm","core":
{"joined":"Sat 21 February 2015","bandbio":"Just registered. Bio coming soon.","genre":"Popular","subgenre":""}}
ISSUE:
Using json_decode and foreach simply want to echo the items in the array.
json_decode(file_get_contents('http://api.mutrs.me/?artists'), TRUE);
foreach($result as $item){
$item->muid;
}
Host:
Checked json_last_error it returns 0
Checked json_last_error_msg it returns No Error
Client:
Checked json_last_error it returns 4
Checked json_last_error_msg it returns Syntax Error
jsondecode converts to array not an standard class object
try this
first $result = json_decode($object , true);
then for your item
$varname = $item['muid'];
Test this compared to Your Code:
<?php
$data = '{"muid":"IM5LGM02MFS8RJLKGY9W","bandname":"Marbles For Zen","core":{"joined":"Sun 01 March 2015","bandbio":"Zen And Marbles","genre":"Rhythm Blues","subgenre":"Dixie Rhythm"}}';
var_dump(json_decode($data , true));
?>

Json Decode Presentation With Category

I got these Json data:
[{"category":"Pizza","name":"Beef Pronto","desc":"Description of Beef Pronton here","price":"12"},
{"category":"Drink","name":"Cool Delight","desc":"Description of Coold Delight here","price":"5"},
{"category":"Drink","name":"Cola","desc":"Description of Cola","price":"4"}
]
With Javascript I have successfully managed data to present as follow:
Pizza
-Beef Pronto: Description of Beef Pronton here: 12
Drink
-Cool Delight: Description of Coold Delight here: 5
-Cola: Description of Cola: 4
any Idea how to do it with PHP ?
-->Ok guys, this is How I do it with PHP:
<?
$listedmenuJSON = '[{"category":"Pizza","name":"Beef Pronto","desc":"Description of Beef Pronton here","price":"12"},
{"category":"Drink","name":"Cool Delight","desc":"Description of Coold Delight here","price":"5"},
{"category":"Drink","name":"Cola","desc":"Description of Cola","price":"4"}
]';
$json_decoded = json_decode($listedmenuJSON);
foreach ($json_decoded as $categoryvalue){
//echo $categoryvalue->category."<br/>";
$tempcategoryvalue[] = $categoryvalue->category;
$arrunique = array_unique($tempcategoryvalue);
}
foreach ($arrunique as $tmpcategory){
echo '<br/><b>'.$tmpcategory.'</b></br>';
foreach ($json_decoded as $tempo){
if($tempo->category == $tmpcategory){
echo $tempo->name.'<br/>';
echo '<i>'.$tempo->desc.'.......</i>';
echo $tempo->price.'<br/>';
}
}
}
?>
It will generate as following:
Pizza
Beef Pronto
Description of Beef Pronton here.......12
Drink
Cool Delight
Description of Coold Delight here.......5
Cola
Description of Cola.......4
If you got json in PHP Code Use Following line to convert json to PHP array and manipulate array for desire output
$array = json_decode($json,TRUE);
In javascript user below code to convert your json to array.
var obj = jQuery.parseJSON(responce);
Try using the PHP function 'json_decode' (http://php.net/manual/en/function.json-decode.php). This will create an associative array in PHP. It should be pretty simple to access and manipulate data thereon.
If you use a SQL server then you can select form the table using "group by category"
Else, you can just verify many times the arrays.
SQL:
<?php
$query = "SELECT * FROM 'table'
GROUP BY category
having (category=\"Pizza\");"
--SELECT * FROM 'table'
--GROUP BY category
--having (category="Drink");
if you use this in php you must use sql_query("query")

Categories