I'm trying to create a JSON output for a PHP website project. I have done quite a bit of research that ended up completely confusing me in the end.
First of, I'm not sure what would be best between PDO or mysqli but I had to move forward and go with PDO. I understand the process of connecting to the server - selecting the database and table. I'm sturggling with outputing the data in the actual nested JSON format that I so cafully planned.
While I am not 100% sure I got it all right
I think I just need to keep doing it with the right code
until everythy makes sense...
Please help!
I am looking to get to somthing like this for my JSON output:
maincategory = {
"subcategory1" : {
"group" : {
"subgroup" :{
"name" : "Jason Lengstorf",
"age" : "24","gender" : "male",
"height" : "6.3",
"weight" : "164lbs"
}
}
},
"subcategory2" : {
"group" : {
"subgroup" :{
"name" : "Jason Lengstorf",
"age" : "24","gender" : "male",
"height" : "6.3",
"weight" : "164lbs"
}
}
}
}
Thanks in advance for your help!
Related
I have a problem with fetching the correct data from a decoded JSON file. I don't know if my question is correct since I don't really know what I am doing for the moment.
So, this is what I don't want to do.
$ln = 'https://api.steamprices.net/v2/csgoprices/?id='.market_hash_name.'&key=XXX';
$link1 = file_get_contents($ln);
$myarray1 = json_decode($link1, true);
echo $myarray1['median_price'];
I am trying to get the price for every steam skin that's being loaded in my code. What this code does is that it loads this api link for every item I load. So if I have 50 items, this link will be loaded 50 times, which is not accepted by the API.
What I want to do, is that I want to load it once, and fetch the prices for every item from that exact link. That link would look like this:
https://api.steamprices.net/v2/csgoprices/?&key=XXX
So, lets say I load it once, and then when I want to apply market_hash_name to it, how do I do?
I assume it is something like this.
$priceJson = file_get_contents('https://api.steamprices.net/v2/csgoprices/?key=XXX');
$priceData = json_decode($priceJson, true);
echo $priceData[''.$market_hash_name.'']['price'];
But it doesn't seem to work. I am sorry for this messy explanation, I an unfamiliar with this.
Note that an example response for the api link looks like this:
{
"-r-H1Z1 Shirt": {
"price": 0.11,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6AbXTJ8PDm57EliZdK7KLPuuh3dxC3m4m0ihzss0MKE6NtIt4qs-JukOX73WgETXYze_pxEBA",
"game": "h1z1"
},
"2016 Invitational Crate": {
"price": 0.09,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6APSjJ6BjX9rGBYZ9ioCPzysSX6hNNacA",
"game": "h1z1"
},
"ANGRYPUG Motorcycle Helmet": {
"price": 0.17,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6AbXTJ8PDm57EliZdK7KLPuuh3WySnxyXoUgz870MKd7sFTkZq98oW1ORiqAVsCUYfbNu3SUQqvUSGyY__iEw",
"game": "h1z1"
},
Another output
{
"name":"Aces High Pin",
"price":1210,
"have":2,
"max":9,
"rate":95,
"tr":0
}
Well, the json string you provide isn't valid but something like this may help you
<?php
$jsonData=file_get_contents("json.file"); // simply contains your json string as posted
$jsonArray=json_decode($jsonData,true);
$jsonObject=json_decode($jsonData);
$list_of_MHN=array("2016 Invitational Crate","ANGRYPUG Motorcycle Helmet");
print_r($jsonArray);
exit;
foreach($jsonArray as $hash_name=>$arr){
if(in_array($hash_name,$list_of_MHN)){
print_r($arr);
}
}
for($i=0;$i<count($list_of_MHN);$i++){
if(isset($jsonArray[$list_of_MHN[$i]])){
print_r($jsonArray[$list_of_MHN[$i]]);
}
}
for($i=0;$i<count($list_of_MHN);$i++){
if(isset($jsonObject->$list_of_MHN[$i])){
print_r($jsonObject->$list_of_MHN[$i]);
}
}
?>
I have a php script that's trying to create a record in a CloudKit database.
It returns this error:
object(stdClass)#1 (3) { ["uuid"]=> string(36)
"c70072a1-fab6-491b-a68f-03b9056223e1" ["serverErrorCode"]=>
string(11) "BAD_REQUEST" ["reason"]=> string(62)
"BadRequestException: Unexpected input at [line: 2, column: 10]" }
I presume this tells me exactly what the problem is, but I don't know how to interpret it. Where is line 2 and column 10?
I think its related to the JSON I'm sending in the create record request.
$url = 'https://api.apple-cloudkit.com/database/1/' . $CONTAINER . '/development/public/records/modify';
$opDict = '{"operationType": "create",
"record":"Artists",
"fields": {"firstName":{"value":"Mei"},
"lastName": {"value":"Chen"},
"principalDiscipline": {"value":""},
"secondaryDiscipline":{"value":""}},
"recordName":"Mei Chen"}';
$body = '{"operations":['.$opDict.']}';
echo $body;
When I check the output from $body
{"operations":[{"operationType": "create", "record":"Artists",
"fields": {"firstName":{"value":"Mei"}, "lastName": {"value":"Chen"},
"principalDiscipline": {"value":""},
"secondaryDiscipline":{"value":""}}, "recordName":"Mei Chen"}]}
it passes JSON lint, so I am not sure it is a JSON problem.
Can someone explain to me how to interpret the error I'm getting from CloudKit. The docs are a little vague on errors.
I got absolutely no clue about CloudKit, but I found this documentation page with the followin example:
{
"operationType" : "create",
"record" : {
"recordType" : "Artist",
"fields" : {
"firstName" : {"value" : "Mei"},
"lastName" : {"value" : "Chen"}
}
"recordName" : "Mei Chen"
},
}
which definitely differs from what you try to send, both in terms of data structure
(your record is not a dictionary) and content (you have no recordType).
So while your JSON is syntactically correct, you are simply sending invalid content data wrapped in valid JSON which is most likely the reason you are seeing the error message.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a PHP script and JSON object with some values is being passed in the the PHP get function. I have tried different ways to decode JSON but failed.
The code I have tried is :
$get_order_info = $_GET['orderInfo'];
$order_json = json_decode($get_order_info, true);
echo $order_json->{'mealsInfo'};
The JSON string is :
{
"mealsInfo" : [
{
"DrinkSize" : 1,
"MealQuantity" : 1,
"MealId" : "57",
"addons" : [
{
"addOnID" : 1,
"addonTitle" : "spicy"
},
{
"addOnID" : 3,
"addonTitle" : "Thin Base"
}
],
"FriesSize" : 2
}
],
"TransactionID" : "56",
"OrerType" : "PickUp",
"frenchiseInfo" : {
"storeName" : "Dubai Downtown Franchise",
"OrderCollectionTime" : "06:12:50 PM",
"FranchiseId" : "4"
},
"customerinfo" : {
"Instructions" : "Test instruction",
"CustomerName’" : "Talat",
"Area" : "al Riga",
"City" : "Dubai",
"Phone" : "0559467800",
"Email" : "test#test.com",
"Address" : "al nouf tower"
},
"status" : "pending",
"totalPrice" : 51
}
Can somebody please help me to decode it in a correct way?
Thanks in advance !
You are passing true as second parameter to json_decode, it will return and array not object. Try with -
$order_json = json_decode($get_order_info, true);
echo $order_json['mealsInfo'][0]['DrinkSize'];
$get_order_info = $_POST['orderInfo'];
$order_json = json_decode($get_order_info, true);
echo $order_json->{'mealsInfo'};
Try this.
$order_json = json_decode($get_order_info, true);
var_dump($order_json->{'mealsInfo'});
I am using an api which is giving me a very strange json format.. i'm posting its data which i am getting thru it..
info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "f53762dab34022e9d851ab71e0bf166f" };
I'm trying to print this data in php but i'm not able to do that..nothing is showing on my webpage,....
My code are..
First i tried,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
echo $info;
?>
My second attempt was,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
$info->h;
?>
My last attempt was,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
$info['h'];
?>
Nothing is happening..
please somebody help me
API Url converted...
The page is sending
"info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "058ce93db26fce4a9f1cb41ae2e7c1bb" };"
You cannot use json_decode on this because the info = and the ; at the end are not json. You have to strip the info = and the ;.
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info = file_get_contents($url);
$info = trim($info, "info = ");
$info = rtrim($info, ";");
$json = json_decode($info, true);
echo $json['status'];
The data I got from the URL in your example is
info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "5cddd4d1667f24aa9a0f5a6cc21e24e3" };
That's an executable JavaScript snippet, not actually JSON. The reason your php is failing is due to the 'info =' part... json_encode returns null on decoding failure.
While this is an assignment of a variable to a JavaScript object, that would work as JSON too if you removed the 'info =' and semicolon. Assuming the responses are predictable, you could do this with php str_replace, but finding an API that returns JSON for your source would be a more reliable and clean solution.
If you're getting NULL when you var_dump($info) on the second line as you mentioned in comments, then file_get_contents() doesn't retrieve the data.
It's most likely because allow_url_fopen is set to false in PHP.ini
From the json_decode() documentation:
Takes a JSON encoded string and converts it into a PHP variable.
If 2nd parameter is set to true it returns an array !
SO your first and second attempt is wrong.! It should work third attempt. Just check if you retrieve the data.
here is the JSON data for my auto complete
{ "list" : [ {
"genericIndicatorId" : 100,
"isActive" : false,
"maxValue" : null,
"minValue" : null,
"modificationDate" : 1283904000000,
"monotone" : 1,
"name":"Abbau",
"old_name" : "abbau_change_delete_imac",
"position" : 2,
"systemGraphics" : "000000",
"unitId" : 1,
"valueType" : 1,
"description" : "Abbau",
"weight" : 1
}]}
and the code which i wrote is
$("#<portlet:namespace />giName").autocomplete({
source :`enter code here` function( request, response ) {
$.post(
"<%=AJAXgetGIs%>",
{
"<%=Constants.INDICATOR_NAME%>" : request.term,
"<%=Constants.SERVICE_ID%>" : <%=serviceId%>
},
function( data ) {
response( $.map( data.list, function( item ) {
//alert(item.name + " || " + item.genericIndicatorId);
item.value = item.name;
return item;
}));
},
"json"
);
},
minLength : 2
i am using jquery-ui-1.8.14.autocomplete.min.js plugin for auto complete
the problem i am getting is it is not showing all the matched results in new browsers.
for example if i type "an" in which should matches to the "anzahl" keyword, the fire bug is showing error like "bad control character literal in a string". results are showing for the letters "as,sa....". any help would be appriciated
thank you
The error message means you have control characters in your JSON response (something like \n, \t, etc). Newlines and the other control characters are not allowed in JSON strings, according to ECMA262 5ed. You can fix it rather easily by escaping or removing those characters, either from PHP or from Javascript.
Here you can find an example of how you can fix it from PHP, as the problem most likely comes from json_encode (which I assume you're using): http://codepad.org/Qu7uPt0E
As you can see, json_encode doesn't escape the \n so you have to do it manually before outputting.
Now for the mistery related to older browsers. If you look at jQuery's parseJSON function you'll notice that it first tries to parse the string with the browser's builtin JSON object and if it doesn't find any, it will just do a (sort of) eval (which will work even with newlines). So it probably works for you on Firefox < 3.5 or IE < 8 which don't have a native JSON object.
Also, it probably works with other search terms (like as, etc) simply because they don't include a result which has control characters.
Adding to draevors correct answer.
Look at downloading the JSON2 library
https://github.com/douglascrockford/JSON-js
That is how i got around this problem