I am trying to output a JSON string using PHP and MySQL but the latitude and longitude is outputting as a string with quotes around the values. This causes an issue when I am trying to add the markers to a google map.
Here is my code:
$sql = mysql_query('SELECT * FROM markers WHERE address !=""');
$results = array();
while($row = mysql_fetch_array($sql))
{
$results[] = array(
'latitude' =>$row['lat'],
'longitude' => $row['lng'],
'address' => $row['address'],
'project_ID' => $row['project_ID'],
'marker_id' => $row['marker_id']
);
}
$json = json_encode($results);
echo "{\"markers\":";
echo $json;
echo "}";
Here is the expected output:
{"markers":[{"latitude":0.000000,"longitude":0.000000,"address":"2234 2nd Ave, Seattle, WA","project_ID":"7","marker_id":"21"}]}
Here is the output that I am getting:
{"markers":[{"latitude":"0.000000","longitude":"0.000000","address":"2234 2nd Ave, Seattle, WA","project_ID":"7","marker_id":"21"}]}
Notice the quotes around the latitude and longitude values.
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
The method JSON. stringify(student) takes the object and converts it into a string. The resulting json string is called a JSON-encoded or serialized or stringified or marshalled object.
The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.
The json_decode() function is used to decode or convert a JSON object to a PHP object.
You could also try
echo json_encode( $results, JSON_NUMERIC_CHECK );
Some reference:
PHP JSON constants
$results[] = array(
'latitude' => (float)$row['lat'],
'longitude' => (float)$row['lng'],
'address' => $row['address'],
'project_ID' => $row['project_ID'],
'marker_id' => $row['marker_id']
);
latitude AND longitude should be a float number, but you could try this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With