Jump to content

Creating a proper JSON file with PHP

SJBijzitter

<?php	$username = "a";	$password = "b";	$base_url = "c";		$info = array();	$json = array();	$xml = new SimpleXMLElement("https://".$username.":".$password."@".$base_url, null, true); //Security risk accepted	foreach ($xml->Station as $station) {		if (strpos($station->Type, "ntercity") !== false) { //Deliberately left out the 'i' in 'intercity' because of inconsistencies on NS' side.			$info["name"] = $station->Namen->Lang;			$info["latitude"] = $station->Lat;			$info["longitude"] = $station->Lon;			array_push($json, json_encode($info));		}	}		file_put_contents("stations.json", json_encode($json, JSON_FORCE_OBJECT));?>
Actual output:

{"0":"{\"name\":{\"0\":\"'s-Hertogenbosch\"},\"latitude\":{\"0\":\"51.69048\"},\"longitude\":{\"0\":\"5.29362\"}}","1":"{\"name\":{\"0\":\"Aachen Hbf\"},\"latitude\":{\"0\":\"50.7678\"},\"longitude\":{\"0\":\"6.091499\"}}","2":"{\"name\":{\"0\":\"Aime-la-Plagne\"},\"latitude\":{\"0\":\"45.55438\"},\"longitude\":{\"0\":\"6.64869\"}}",//etc}
Wanted* output:

{{"name":"'s-Hertogenbosch","latitude":"51.69048","longitude":"5.29362"},{"name":"Aachen Hbf","latitude":"50.7678","longitude":"6.091499"},{"name":"Aime-la-Plagne","latitude":"45.55438","longitude":"6.64869"},//etc}
But I have no idea how to do this with PHP, I normally program desktop applications =-/

I would dislike having to use anything but the default PHP 5 installation, downloading libraries would be a bit of a bummer. But yeah, I'm requesting a push in the right direction here =-/

*Doesn't have to be exactly like this, but I just don't want any useless 'keys' (or whatever you want to call them) in my output.

"I see now that the circumstances of one's birth are irrelevant. It is what you do with the gift of life that determines who you are."

-Mewtwo

Link to comment
Share on other sites

Link to post
Share on other sites

i think that simple string concatenation could suffice

<?php	$username = "a";	$password = "b";	$base_url = "c";		$json = "{\n";	$xml = new SimpleXMLElement("https://".$username.":".$password."@".$base_url, null, true); //Security risk accepted	foreach ($xml->Station as $station) 		if (strpos($station->Type, "ntercity") !== false) { //Deliberately left out the 'i' in 'intercity' because of inconsistencies on NS' side.			if($json != "{\n")		// if it's not the first one				$json .= ",\n";		// add a comma and go to the new line			$json .= '{"name":"' . $station->Namen->Lang . '","latitude":"' . $station->Lat . '","longitude":"' . $station->Lon . '"}';		}		file_put_contents("stations.json", $json);?>
Link to comment
Share on other sites

Link to post
Share on other sites

Just a note regarding the "useless keys": Could you not use something

that's now in the object itself and use it as the key? For example

the station name (or whetever else is unique to each object)? That

way you don't have any redundant info and can avoid the "0" etc. array

index keys (having keys with actual useful info in them instead).

EDIT:

I should note I've only worked with JSON in Perl, not PHP (I do have

experience with PHP, just not PHP+JSON), just in case that's of

relevance.

BUILD LOGS: HELIOS - Latest Update: 2015-SEP-06 ::: ZEUS - BOTW 2013-JUN-28 ::: APOLLO - Complete: 2014-MAY-10
OTHER STUFF: Cable Lacing Tutorial ::: What Is ZFS? ::: mincss Primer ::: LSI RAID Card Flashing Tutorial
FORUM INFO: Community Standards ::: The Moderating Team ::: 10TB+ Storage Showoff Topic

Link to comment
Share on other sites

Link to post
Share on other sites

^- yeah that would work but it'd be improper in my opinion.

I just debugged a shitload more and it seems all I had to do was cast the array's data to string, because for some reason PHP doesn't do that by itself.

"I see now that the circumstances of one's birth are irrelevant. It is what you do with the gift of life that determines who you are."

-Mewtwo

Link to comment
Share on other sites

Link to post
Share on other sites

You're encoding $info as a json string and then pushing it onto $json... There is no need for this. The json encoder will just recognize it as an array of strings, which is exactly what has happened.

Take $info and push the array itself onto $json, don't encode it first... then encode the whole of $json, and you should get the expected JSON array out.

Also, you're not going to be able to avoid the keys if you use JSON_FORCE_OBJECT... if you don't have keys on an object there is no way to reference the members. Take that flag off and you'll get an array without any keys.

Link to comment
Share on other sites

Link to post
Share on other sites

Have a look at json_encode. That should give you some ideas on how to generate a json file properly and why you're getting these slashes.

 

The way you'd be getting rid of these slashes is by disabling the by default enabled escaped slashes, I would recommend you to have it enabled since this would avoid interferences with quotes. If you still choose to wanting to disable the escaped slashes then you can do so in the json_encode function by parsing JSON_UNESCAPED_SLASHES after the data.

 

So you would have

json_encode($data, JSON_UNESCAPED_SLASHES);

So the idea behind generating the json data correctly is to obtain values from essentially an array and have that parsed into a json object. This then would be returned as a string and then you'd be able to echo it out depending on the values.

so for example you may obtain information from a get request and use that to dependently display information related to the values parsed in the get request.

 

So you'd have a php file with some values, these values could be anything from an dynamic to a static value. Just literally anything.

$fromPHPdocs = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

These values would then be parsed into the json_encode function which would obtain that data and convert it into a correct json object. This would be done simply like so.

json_encode($fromPHPdocs);

The json_encode method itself returns the json object as a string, so you'd either have to store it into a variable or which I'd recommend you to do is to directly echo it out once you'd done obtaining the data.

This would be very straight forward to do so and I believe that you'd know how to do this and if you don't then you simply do as following.

echo json_encode($fromPHPdocs);

If you were to echo this correctly then you'd have the following results after accessing the php page {"a":1,"b":2,"c":3,"d":4,"e":5}

 

And ofcourse like I were saying, this data can be dynamically generated so if you were to parse dynamic values into the array then you'd have a different output coming from the php page depending on the values parsed and also like I was saying you'd be able to implement this with a get request so you'd have the dynamic data vary depending on the values parsed in the get request.

 

So for example if you were to obtain the values listOfLetters, maximumValue in the get request like so https://localhost.com/thePHPfileGeneratingJSON.php?listOfLetters=a+c+e&maximumValue=3

Then you could have the php file obtain these values and use them to dynamically generate the json data and echo it.

If you were to use these values correctly and only list the mentioned characters and mentioned maximum values then you would have it just return {"a":1, "c":3}

 

So the idea was that you toke these values and only displayed the mentioned Letters and only showed values up to the mentioned maximum value.

 

If you don't know how to use get request then read up on it since it's very useful especially when generating a JSON file 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×