php json format - php

I have a json response in this url, which I have to validate from this site.
I have stuck my head through many solutions,and I don't know what's wrong here.
I am very thankful for any help suggestions.
this is the code
header('Content-type: application/json');
$obj=array();
$UID=isset($_REQUEST['UID'])?$_REQUEST['UID']:'';
if($UID!='')
{
$sound_cloud=getLatestSound($UID);
if($sound_cloud==false)
{
$sound_cloud['status']="No Record Found";
$obj['status']="No Record Found";
}
else
{
$sound_cloud['status']="successfull";
}
}
else
{
$sound_cloud['errors']="required UID";
}
print stripslashes(json_encode($sound_cloud));
exit;

<?php
$json = '{"stream_url":"http://api.soundcloud.com/tracks/74950626/stream?client_id=b45b1aa10f1ac2941910a7f0d10f8e28","title":"Klaypex-Jump","status":"successfull"}';
$arrayval = json_decode($json);
print_r($arrayval);
// OR
$url = 'http://knowyourdj.staging.techliance.com/webservices?action=GetSoundCloud&UID=1';
$json = file_get_contents($url);
$arrayval = json_decode($json);
print_r($arrayval);
?>
Result:
stdClass Object ( [stream_url] => http://api.soundcloud.com/tracks/74950626/stream?client_id=b45b1aa10f1ac2941910a7f0d10f8e28 [title] => Klaypex-Jump [status] => successfull )

use
$json = file_get_contents('http://knowyourdj.staging.techliance.com/webservices?action=GetSoundCloud&UID=1');//fetch contents from server
$json = json_decode($json); // parse fetched contents
if(!empty($josn)){
print_r($json);
}else{
echo 'no result were found';
}
//lets find what we had parse

echo it, not print. just try~
print stripslashes(json_encode($sound_cloud));
=>
echo stripslashes(json_encode($sound_cloud));
------------------ edit
If this isn't a solution, I think this is a kind of same origin policy problem.
double check your url, it should have same domain with web page server.
refrence - same origin policy
use jquery jsonp,

You can make an ajax call with jquery to your php like this
$.ajax({
type:"POST",
url:'/example.php', //your url
data:{'seguros':a, 'esp':esp,'cont':cont}, //your variables
success: function(data){
//handle your answer here
}
});

Related

Get value from Json object (url) in php

I have a json i am fetching remotely in php,
the Json returned is as follow:
{
"base_currency_code":"USD",
"base_currency_name":"United States dollar",
"amount":"1.0000",
"updated_date":"2022-01-30",
"rates":{
"KWD":{
"currency_name":"Kuwaiti dinar",
"rate":"0.3030",
"rate_for_amount":"0.3030"
}
},
"status":"success"
}
the i try to get the specific value from key : rate :
$url='https://...';
$json = file_get_contents($url);
$obj = json_decode($json,true);
echo $obj['rates']['KWD']['rate'];
but I have no output, when I would like to have 0.3030. Why is this?
test.json
{
"base_currency_code":"USD",
"base_currency_name":"United States dollar",
"amount":"1.0000",
"updated_date":"2022-01-30",
"rates":{
"KWD":{
"currency_name":"Kuwaiti dinar",
"rate":"0.3030",
"rate_for_amount":"0.3030"
}
},
"status":"success"
}
test.php
<?php
$url='test.json';
$json = file_get_contents($url);
$obj = json_decode($json,true);
echo $obj['rates']['KWD']['rate'];
Result 0.3030
If it is not working, you cannot access the site remotely.
try it and make sure it works
<?php
$url='https......';
$json = file_get_contents($url);
echo $json;

Saving data across multiple lines JSON

Currently I have PHP and JS save my data in a JSON.
Below is the code for it:
PHP:
<?php
$jsonString = file_get_contents('passwords.json');
$data = json_decode($jsonString, true);
// get the q parameter from URL
$q = $_REQUEST["q"];
$item = $_REQUEST["item"];
// or if you want to change all entries with activity_code "1"
foreach ($data["passwords"] as $key => $password) {
echo $data["passwords"][$key]['timesToUse'] - 1;
if ($password['password'] == $q) {
$data["passwords"][$key]['timesToUse'] = $data["passwords"][$key]['timesToUse'] - 1;
$data["passwords"][$key]['winningItem'] = $item;
}
}
$newJsonString = json_encode($data);
file_put_contents('passwords.json', $newJsonString);
?>
JS:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "passwords.php?q="+passwords[i].password+"&item="+winningItem.getFullName(), true);
xmlhttp.send();
The issue that I am having is that initially my JSON file looks like this:
{"password":"IS360H","timesToUse":1,"winningItem":""},
{"password":"AGRD33","timesToUse":1,"winningItem":""},
{"password":"4BX0FV","timesToUse":1,"winningItem":""},
{"password":"99NOTX","timesToUse":1,"winningItem":""},
{"password":"X2Z8BO","timesToUse":1,"winningItem":""},
{"password":"R9G4Q0","timesToUse":1,"winningItem":""},
{"password":"CG9RGT","timesToUse":1,"winningItem":""},
As you can see it is nice and neat and is sitting at 1 password per line. However once the file gets modified, it turns to this:
{"password":"IS360H","timesToUse":0,"winningItem":"counterUAV"},{"password":"AGRD33","timesToUse":0,"winningItem":"sentryGun"},"password":"4BX0FV","timesToUse":0,"winningItem":"chopperGunner"},"password":"99NOTX","timesToUse":1,"winningItem":""},{"password":"X2Z8BO","timesToUse":1,"winningItem":""}, {"password":"R9G4Q0","timesToUse":1,"winningItem":""},"password":"CG9RGT","timesToUse":1,"winningItem":""},
What do I need to do to make my JSON file preserve the line breaks?
Thank you!
There is option JSON_PRETTY_PRINT available in json_encode function, if you are using same for encoding json. Try following:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
Read more about json_encode

API Data Return to HTML

I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.

Struggling with a small json and php to get IP

PHP
<?php
header('Content-type: application/json');
$return['ip'] = $_SERVER['REMOTE_ADDR'];
$results[] = array(
'ip' => $return['ip']
);
echo json_encode($results);
?>
jQuery
$.getJSON("http://domain.com/json/",
function(data){
console.log(data.ip);
});
});
But when I run the jQuery I've checked Fire bug and it says the following
GET http://domain.com/json/ 200 OK 81ms
And doesn't respond with the IP that I requested for. Have I missed something?
UPDATED CODE
PHP
<?php
header('Content-type: application/json');
$return['ip'] = $_SERVER['REMOTE_ADDR'];
$results = array(
'ip' => $return['ip']
);
echo json_encode($results);
?>
jQuery
$.getJSON("http://domain.com/json/", function(data){
console.log(data.ip);
});
Firebug Error
SyntaxError: invalid label {"ip":"XXX.XXX.XXX.X"}
An arrow points at the first quotation mark just before the word ip.
You are returning:
[{'ip': 'XXX.XXX.XXX.XXX'}]
But you are treating it as if you are returning:
{'ip': 'XXX.XXX.XXX.XXX'}
You either need to change your JavaScript to console.log(data[0].ip) or change your PHP to: $results = array( ... ); rather than $results[] = array( ... );
Either will fix your problem. :)

Writing JSON object to .json file on server

I'm trying to write my JSON object to a .json file on the server. The way I'm doing this now is:
JavaScript:
function createJsonFile() {
var jsonObject = {
"metros" : [],
"routes" : []
};
// write cities to JSON Object
for ( var index = 0; index < graph.getVerticies().length; index++) {
jsonObject.metros[index] = JSON.stringify(graph.getVertex(index).getData());
}
// write routes to JSON Object
for ( var index = 0; index < graph.getEdges().length; index++) {
jsonObject.routes[index] = JSON.stringify(graph.getEdge(index));
}
// some jQuery to write to file
$.ajax({
type : "POST",
url : "json.php",
dataType : 'json',
data : {
json : jsonObject
}
});
};
PHP:
<?php
$json = $_POST['json'];
$info = json_encode($json);
$file = fopen('new_map_data.json','w+');
fwrite($file, $info);
fclose($file);
?>
It is writing fine and the information seems to be correct, but it is not rendering properly. It is coming out as:
{"metros":["{\\\"code\\\":\\\"SCL\\\",\\\"name\\\":\\\"Santiago\\\",\\\"country\\\":\\\"CL\\\",\\\"continent\\\":\\\"South America\\\",\\\"timezone\\\":-4,\\\"coordinates\\\":{\\\"S\\\":33,\\\"W\\\":71},\\\"population\\\":6000000,\\\"region\\\":1}",
... but I'm expecting this:
"metros" : [
{
"code" : "SCL" ,
"name" : "Santiago" ,
"country" : "CL" ,
"continent" : "South America" ,
"timezone" : -4 ,
"coordinates" : {"S" : 33, "W" : 71} ,
"population" : 6000000 ,
"region" : 1
} ,
Why am I getting all of these slashes and why it is all on one line?
You are double-encoding. There is no need to encode in JS and PHP, just do it on one side, and just do it once.
// step 1: build data structure
var data = {
metros: graph.getVerticies(),
routes: graph.getEdges()
}
// step 2: convert data structure to JSON
$.ajax({
type : "POST",
url : "json.php",
data : {
json : JSON.stringify(data)
}
});
Note that the dataType parameter denotes the expected response type, not the the type you send the data as. Post requests will be sent as application/x-www-form-urlencoded by default.
I don't think you need that parameter at all. You could trim that down to:
$.post("json.php", {json : JSON.stringify(data)});
Then (in PHP) do:
<?php
$json = $_POST['json'];
/* sanity check */
if (json_decode($json) != null)
{
$file = fopen('new_map_data.json','w+');
fwrite($file, $json);
fclose($file);
}
else
{
// user has posted invalid JSON, handle the error
}
?>
Don't JSON.stringify. You get a double JSON encoding by doing that.
You first convert your array elements to a JSON string, then you add them to your full object, and then you encode your big object, but when encoding the elements already encoded are treated as simple strings so all the special chars are escaped. You need to have one big object and encode it just once. The encoder will take care of the children.
For the on row problem try sending a JSON data type header: Content-type: text/json I think (didn't google for it). But rendering will depend only on your browser. Also it may be possible to encode with indentation.
Probably too late to answer the question. But I encountered the same issue. I resolved it by using "JSON_PRETTY_PRINT"
Following is my code:
<?php
if(isset($_POST['object'])) {
$json = json_encode($_POST['object'],JSON_PRETTY_PRINT);
$fp = fopen('results.json', 'w');
fwrite($fp, $json);
fclose($fp);
} else {
echo "Object Not Received";
}
?>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
<?php
$str = file_get_contents('data.json');//get contents of your json file and store it in a string
$arr = json_decode($str, true);//decode it
$arrne['name'] = "sadaadad";
$arrne['password'] = "sadaadad";
$arrne['nickname'] = "sadaadad";
array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
$str = json_encode($arr);
//now send evrything to ur data.json file using folowing code
if (json_decode($str) != null)
{
$file = fopen('data.json','w');
fwrite($file, $str);
fclose($file);
}
else
{
// invalid JSON, handle the error
}
?>
<form method=>
</body>
data.json
{
"employees":[
{
"email":"11BD1A05G9",
"password":"INTRODUCTION TO ANALYTICS",
"nickname":4
},
{
"email":"Betty",
"password":"Layers",
"nickname":4
},
{
"email":"Carl",
"password":"Louis",
"nickname":4
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
}
]
}

Categories