JSON PHP: Is this the correct way? - php

I just wanted some input about my use of JSON.
<?php
header('Content-Type: text/plain');
//results
$results = array();
for($i=0;$i<20;$i++)
{
$result = array();
$result['name'] = 'Test Season '.ceil(($i+1)/13).' Episode '.(($i%13)+1);
//$result['torrent'] = 'https://www.example.com/?id='.$i.'&key='.uniqid();
$result['torrents'] = array();
$c = mt_rand(1,4);
for($j=0;$j<$c;$j++)
{
$torrent = array();
$torrent['url'] = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent['codec'] = $j%2 == 0 ? 'xvid' : 'h264';
$torrent['resolution'] = '720p';
$result['torrents'][] = $torrent;
}
$results[] = $result; //push
}
echo json_encode($results);
?>
This is just some test code, not an actual implementation. Am I using JSON correctly and too the fullest? Or is some better method of doing this?
I have legal torrents that I'd like to do some JSON with.
Torrents are grouped by name which contain multiple torrents (actual links to data). And other information such as codec etc.
This is my first time actually outputting JSON, would XML be better?
Are there any guides on this topic (hopefully not entire books)?
Thanks.

What you doing is right. I like to use the StdClass to make objects rather than key value arrays, just cause it looks sexier! E.g.
$torrent = new StdClass();
$torrent->url = 'https://www.example.com/?id='.uniqid().'&key='.md5(uniqid());
$torrent->codec = $j%2 == 0 ? 'xvid' : 'h264';
$torrent->resolution = '720p';
$result['torrents'][] = $torrent;
As you say you don't need to read a whole book on the matter, I would have a look here http://php.net/manual/en/book.json.php to get to grips with the basics of JSON.
In terms of JSON vs XML, I find it far easier to represent data as JSON as it is easier to fetch the specific data you want much in the same way you can access the info in a stdClass object.
[EDIT]
And as Stefan Gehrig says make sure you define your content type as "application/json".

Absolutely fine. You could only change the MIME type to be RFC 4627 compliant though: application/json.

Related

PHP foreach statement issue with accessing XML data

First, I am pretty clueless with PHP, so be kind! I am working on a site for an SPCA (I'm a Vet and a part time geek). The PHP accesses an xml file from a portal used to administer the shelter and store images, info. The file writes that xml data to JSON and then I use the JSON data in a handlebars template, etc. I am having a problem getting some data from the xml file to outprint to JSON.
The xml file is like this:
</DataFeedAnimal>
<AdditionalPhotoUrls>
<string>doc_73737.jpg</string>
<string>doc_74483.jpg</string>
<string>doc_74484.jpg</string>
</AdditionalPhotoUrls>
<PrimaryPhotoUrl>19427.jpg</PrimaryPhotoUrl>
<Sex>Male</Sex>
<Type>Cat</Type>
<YouTubeVideoUrls>
<string>http://www.youtube.com/watch?v=6EMT2s4n6Xc</string>
</YouTubeVideoUrls>
</DataFeedAnimal>
In the PHP file, written by a friend, the code is below, (just part of it), to access that XML data and write it to JSON:
<?php
$url = "http://eastbayspcapets.shelterbuddy.com/DataFeeds/AnimalsForAdoption.aspx";
if ($_GET["type"] == "found") {
$url = "http://eastbayspcapets.shelterbuddy.com/DataFeeds/foundanimals.aspx";
} else if ($_GET["type"] == "lost") {
$url = "http://eastbayspcapets.shelterbuddy.com/DataFeeds/lostanimals.aspx";
}
$response_xml_data = file_get_contents($url);
$xml = simplexml_load_string($response_xml_data);
$data = array();
foreach($xml->DataFeedAnimal as $animal)
{
$item = array();
$item['sex'] = (string)$animal->Sex;
$item['photo'] = (string)$animal->PrimaryPhotoUrl;
$item['videos'][] = (string)$animal->YouTubeVideoUrls;
$item['photos'][] = (string)$animal->PrimaryPhotoUrl;
foreach($animal->AdditionalPhotoUrls->string as $photo) {
$item['photos'][] = (string)$photo;
}
$item['videos'] = array();
$data[] = $item;
}
echo file_put_contents('../adopt.json', json_encode($data));
echo json_encode($data);
?>
The JSON output works well but I am unable to get 'videos' to write out to the JSON file as the 'photos' do. I just get '/n'!
Since the friend who helped with this is no longer around, I am stuck. I have tried similar code to the foreach statement for photos but am getting nowhere. Any help would be appreciated and the pets would appreciate it as well!
The trick with such implementations is to always look what you have got by dumping data structures to a log file or command line. Then to take a look at the documentation of the data you see. That way you know exactly what data you are working with and how to work with it ;-)
Here it turns out that the video URLs you are interested in are placed inside an object of type SimpleXMLElement with public properties, which is not really surprising if you look at the xml structure. The documentation of class SimpleXMLElement shows the method children() which iterates through all children. Just what we are looking for...
That means a clean implementation to access those sets should go along these lines:
foreach($animal->AdditionalPhotoUrls->children() as $photo) {
$item['photos'][] = (string)$photo;
}
foreach($animal->YouTubeVideoUrls->children() as $video) {
$item['videos'][] = (string)$video;
}
Take a look at this full and working example:
<?php
$response_xml_data = <<< EOT
<DataFeedAnimal>
<AdditionalPhotoUrls>
<string>doc_73737.jpg</string>
<string>doc_74483.jpg</string>
<string>doc_74484.jpg</string>
</AdditionalPhotoUrls>
<PrimaryPhotoUrl>19427.jpg</PrimaryPhotoUrl>
<Sex>Male</Sex>
<Type>Cat</Type>
<YouTubeVideoUrls>
<string>http://www.youtube.com/watch?v=6EMT2s4n6Xc</string>
<string>http://www.youtube.com/watch?v=hgfg83mKFnd</string>
</YouTubeVideoUrls>
</DataFeedAnimal>
EOT;
$animal = simplexml_load_string($response_xml_data);
$item = [];
$item['sex'] = (string)$animal->Sex;
$item['photo'] = (string)$animal->PrimaryPhotoUrl;
$item['photos'][] = (string)$animal->PrimaryPhotoUrl;
foreach($animal->AdditionalPhotoUrls->children() as $photo) {
$item['photos'][] = (string)$photo;
}
$item['videos'] = [];
foreach($animal->YouTubeVideoUrls->children() as $video) {
$item['videos'][] = (string)$video;
}
echo json_encode($item);
The obvious output of this is:
{
"sex":"Male",
"photo":"19427.jpg",
"photos" ["19427.jpg","doc_73737.jpg","doc_74483.jpg","doc_74484.jpg"],
"videos":["http:\/\/www.youtube.com\/watch?v=6EMT2s4n6Xc","http:\/\/www.youtube.com\/watch?v=hgfg83mKFnd"]
}
I would however like to add a short hint:
In m eyes it is questionable to convert such structured information into an associative array. Why? Why not a simple json_encode($animal)? The structure is perfectly fine and should be easy to work with! The output of that would be:
{
"AdditionalPhotoUrls":{
"string":[
"doc_73737.jpg",
"doc_74483.jpg",
"doc_74484.jpg"
]
},
"PrimaryPhotoUrl":"19427.jpg",
"Sex":"Male",
"Type":"Cat",
"YouTubeVideoUrls":{
"string":[
"http:\/\/www.youtube.com\/watch?v=6EMT2s4n6Xc",
"http:\/\/www.youtube.com\/watch?v=hgfg83mKFnd"
]
}
}
That structure describes objects (items with an inner structure, enclosed in json by {...}), not just arbitrary arrays (sets without a structure, enclosed in json by a [...]). Arrays are only used for the two unstructured sets of strings in there: photos and videos. This is much more logical, once you think about it...
Assuming the XML Data and the JSON data are intended to have the same structure. I would take a look at this: PHP convert XML to JSON
You may not need for loops at all.

Parsing JSON with PHP array/object confusion

I am trying to parse this JSON data to print on a fanpage I am working on.
If you look at that JSON link, you will see that the structure is [{key:value,key:value,key:value}]. I recently learned how to parse JSON with a slightly different structure like this JSON file, where the data structure is {"identifier":[{key:value,value,value,value,value}{key:value,value...}]}
Here is my code I am attempting:(I have tried about 10 variations of this with explodes for the commas too)
<?php
$json = file_get_contents('http://live.nhl.com/GameData/SeasonSchedule-20152016.json');
$json = json_decode($json, TRUE);
foreach($json as $d){
$estTime = $d['est'];
echo $estTime;
?>
As I said, I had some success with that other structure of JSON I linked by doing this:
$json = file_get_contents('http://nhlwc.cdnak.neulion.com/fs1/nhl/league/playerstatsline/20152016/2/SJS/iphone/playerstatsline.json');
$json = json_decode($json, TRUE);
$skaterData = $json['skaterData'];
$goalieData = $json['goalieData'];
foreach($skaterData as $d){
$stats = explode(',', $d['data']);
$number = $stats[0];
$position = $stats[1];
$name = $stats[2];
$gp = $stats[3];
$goals = $stats[4];
$assists = $stats[5];
$points = $stats[6];
$plsmns = $stats[7];
$pim = $stats[8];
$shots = $stats[9];
$toi = $stats[10];
$pp = $stats[11];
$sh = $stats[12];
$gwg = $stats[13];
$ot = $stats[14];
Edit: JSON data successfully parsed
The only thing wrong with your code is that you are missing the closing curly bracket to your foreach.
I would strongly recommend paying attention to the error messages you get, often they will let you easily solve the problem. If your server does not display them in the browser (this is usually a good thing on live sites), you will find them in an error log somewhere on the server.
Additionally you may want to use a proper editor with linting (what is linting), which would probably have immediately notified you of this omission one way or another. One such free tool is Atom.

How to use loop in comment section

I have used foreach loop to extract multiple value of user_phone between tab but it will produce error.I dont what is exact formate.
$result = $Admin->select($Admin->newsletter_subscribers,'',"");
print_r($result['user_phone']);
$data="<message-submit-request>
<username>#######</username>
<password>#######</password>
<sender-id>$$$$$$</sender-id>".
foreach($result as $row)
{
"<to>".$row['user_phone']."</to>"
}."<MType></MType>
<message-text>
<text>hi test message 1</text>
</message-text>
</message-submit-request>";
Try this:
$result = $Admin->select($Admin->newsletter_subscribers,'',"");
print_r($result['user_phone']);
$data = "<message-submit-request>
<username>#######</username>
<password>#######</password>
<sender-id>$$$$$$</sender-id>";
foreach($result as $row)
{
$data .= "<to>".$row['user_phone']."</to>";
}
$data .= "<MType></MType>
<message-text>
<text>hi test message 1</text>
</message-text>
</message-submit-request>";
The exact format for string concatenation is shown in the PHP manual under string operators. However I won't elaborate on these directly becasue cerating XML by concatenating strings is a bad idea. For example having characters like <, > and & in your input, you'll run into many problems.
For your use-case SimpleXMLElement is a handy object that allows you to do the same in a much more consisted manner:
// create XML document based on boilerplate
$xml = new SimpleXMLElement('
<message-submit-request>
<username>#######</username>
<password>#######</password>
<sender-id>$$$$$$</sender-id>
<MType></MType>
<message-text>
<text>hi test message 1</text>
</message-text>
</message-submit-request>
');
// add elements where appropriate
foreach($result as $row)
{
$xml->addChild('to', $row['user_phone']);
}
This will ensure that all values are properly encoded. Additionally this can have a magnitude on benefits when you further process the data, e.g. outputting it.
However you haven't shown in your question what follows up with $data so you need to know how to obtain the XML from the SimpleXMLElement as string to make the example complete. Here it is:
$data = $xml->asXML();
See as well the SimpleXML Basic Usage guide in the manual if you'd like to learn more.

Returning a blob with json

I'm trying to create a rest service for my android application where an external database returns items to be stored in the applications local database. I've got everything working except blobs are being returned as null.
this is an example of my jason response.(picture and thumbnail fields are blobs)
{"id":"2","user_id":"1","name":"testing","type":"bouldering","picture":null,"lat":"36","long":"81","alt":"41932","accuracy":"53","thumbnail":null}
Here is my php script to return the data.
<?php
require_once('config.php');
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$sql = 'select * from spot_main';
$results =$mysqli->query($sql);
$spots = array(); //array to parse jason from
while($spot = $results->fetch_assoc()){
$spots[] = $spot;
}
echo json_encode($spots);
?>
Anyone know of a solution to this problem? I know I'm not doing this the most efficient way(better to store images in the filesystem), but I need this to work.
Encode the binary data as base64 before you generate the JSON.
$obj->picture = base64_encode($binaryData);
You can then decode this in your Android application with any base 64 decoder. Since API level 8 there is a built in util class. Otherwise there are plenty of external libs you can use for targetting Android 2.1 or earlier.
you have to make BLOB to base64_encode
while($spot = $results->fetch_assoc()){
$spots[] = $spot;
}
Then prepare a foreach loop like this
foreach($spots as $key=>$value){
$newArrData[$key] = $spots[$key];
$newArrData[$key]['picture'] = base64_encode($spots[$key]['picture']);
$newArrData[$key]['thumbnail'] = base64_encode($spots[$key]['thumbnail']);
}
header('Content-type: application/json');
echo json_encode($newArrData);
It seems that json_encode works with UTF-8 encoded data only. You can use json_last_error() to detect json_encode error.

Parsing JSON string to dictionary swift

I'm trying to access the individual member-fields of a JSON object in PHP from a JSON string but I can't to access the inner-json, all I get is Array.
This is the JSON string
data = (
{
"created_time" = "2018-10-07T04:42:39+0000";
id = 1069496473131329;
name = "NAME_0";
},
{
"created_time" = "2018-09-09T10:31:50+0000";
id = 955684974605664;
name = "NAME_1";
},
At the moment my code is:
$nameString = $_POST["nameData"];
$nameJsonString = json_encode($nameString, JSON_FORCE_OBJECT);
$jsonNameObj = json_decode($nameJsonString, true);
I've been trying to access the individual entry with:
$element = $jsonNameObj['data'][0];
But only receive Array.
Any help would be greatly appreciated,
Cheers :)
After checking the inputted JSON data, I've realised that it doesn't have a consistent form. As opposed to the overall structure being:
JSON -> List -> JSON
Instead, it's:
JSON -> List
The list contains individual elements that can be in a different order. Consequently, calling:
$element = $jsonNameObj['data'][0]['created_time'];
Works sometimes. As there are three-values/object, I can congregate these values into a trio.
I'm sure there's a way to condense this list into a fixed-JSON format but I'm not familiar with how I'd go about that.
At the moment, with a bit of logic on the back-end, I can retrieve the values.
Thanks for your help #Difster and #Osama!

Categories