I have the following code that will print some JSON from mysql database.
However, when i check the JSON output, the JSON is invalid.
This is the JSON out put on my PHP page:
[{
"id": "1",
"title": "test title",
"about": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
"address": "some address goes here",
"lat": "51",
"lon": "0.888",
"distance": {
"miles": 3.973345345,
"kilometers": 6.39345348
}
}][{
"id": "3",
"title": "test title 5",
"about": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
"address": "some address goes here",
"lat": "51",
"lon": "0.256",
"distance": {
"miles": 3.9735000071413,
"kilometers": 6.3947283954928
}
}]
This is my PHP code:
header('Content-type: application/json');
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
$theta = $longitude1 - $longitude2;
$miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos (deg2rad($latitude2)) * cos(deg2rad($theta)));
$miles = acos($miles);
$miles = rad2deg($miles);
$miles = $miles * 60 * 1.1515;
$kilometers = $miles * 1.609344;
return compact('miles','kilometers');
}
$records = array();
/* soak in the passed variable or set our own */
$latitude2 = floatval($_GET['latitude']); //no default
$longitude2 = floatval($_GET['longitude']); //no default
/* grab the posts from the db */
$sql = "SELECT * FROM businesses ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query);
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
{
extract($row);
$latitude = $row['lat'];
$longitude = $row['lon'];
$point1 = array('lat' => number_format ($latitude,4,'.',''), 'long' => number_format ($longitude,4,'.',''));
$point2 = array('lat' => number_format ($latitude2,4,'.',''), 'long' => number_format ($longitude2,4,'.',''));
$distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
$channel = array(
'id' => $id,
'title' => $title,
'about' => $about,
'address' => $address,
'lat' => $latitude,
'lon' => $longitude,
'distance' => $distance,
);
}
$channels = array($channel);
$records[] = $channel;
//$json = json_encode($channel);
//echo $json;
echo '' . json_encode($records, JSON_UNESCAPED_SLASHES) . '';
}
If I have only one record in the database, it works fine but when its more than 1 record, the JSON output is invalid.
Could someone please advice on this issue?
echoafterwhile.while () { {} }?