How Do I read CloudKit Errors? - php

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.

Related

multi level nested JSON output using PHP through MySQL and PDO

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!

PHP XML converter response

im quite new on XML, i am currently work in PHP and i have a request to other server which normaly and always return the callback with XML
In any case i would not talk about how i get the response, but how to convert the XML reponse.
They are two type of the XML response, we could call it as $response
first :
<BASEELEMENT SCHEMA="RESULT" METHOD="ADD-MBX">
<RETURN_VALUE>4</RETURN_VALUE>
<ERROR_DESCRIPTION>
<![CDATA[Error (7004): Login name already exists. Please use another login name.]]>
</ERROR_DESCRIPTION>
</BASEELEMENT>
and the second one is :
<baseelement schema="TIMEOUT" method="ADD-MBX"></baseelement>
i have searched and i got how to convert the xml reponse to obejct or array, which is
$response = new \SimpleXMLElement($response);
after convert :
object(SimpleXMLElement)#256 (3) {
["#attributes"]=>
array(2) {
["SCHEMA"]=>
string(6) "RESULT"
["METHOD"]=>
string(7) "ADD-MBX"
}
["RETURN_VALUE"]=>
string(1) "4"
["ERROR_DESCRIPTION"]=>
object(SimpleXMLElement)#257 (0) {
}
}
as we can see the ERROR_DESCRIPTION become 0.
So i would like to ask, is there any xml converter else simplexml_load_string() or new \SimpleXMLElement()
i cant use that function because i could not get the ERROR_DESCRIPTION
thank you :)
Loading it as you are with -
$response = new \SimpleXMLElement($response);
You can fetch the value quite simply as...
echo (string)($response->ERROR_DESCRIPTION).PHP_EOL;
If you want the full content (as in an XML version)...
echo $response->ERROR_DESCRIPTION->asXML().PHP_EOL;
Using XPath, you can fetch the values by...
echo (string)$response->xpath("//ERROR_DESCRIPTION")[0].PHP_EOL;
The output you are seeing shows that ERROR_DESCRIPTION is an object of SimpleXMLElement type, not that it isn't loaded.

Receive array of numbers in php (JSON)

I would like to get an array from my JSON in php.
This way I get the JSON string from URL in my android application:
JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", paramstodb);
To receive [phone=123] in php I use this:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
That is working for one phonenumber, but now I need more than one phonenumber.
The data in Logcat (reported with "Log.d("to php: ", paramstodb.toString())" ) is displayed as:
to php:﹕ [phone=[0127361744, 0132782422, 0137173813, 0142534646, 0123617637435, 013391339494, 01383375633, 013878942423, 013891748422, 01389487285, 014434354234, 01848481371, 018831789414, 021238133441231, 021371689411, 02183718454, 123, 456]]
How can I get all numbers in an array in php?
This is not working so far:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
$phpArray = json_decode($phone, true);
I hope you can help me again ;-)
If the JSON input to the PHP script really is this JSON
{ "phone": [ "123", "456", "789"] }
then PHP's json_decode should handle it without problems.
You can try this code to see it's actually working and use it to detect where something goes wrong:
// original JSON to send from the client
$jsonString = '{ "phone": [ "123", "456", "789"] }';
// build a query string with the JSON to send
$queryString = "?" . http_build_query(array("phone" => $jsonString));
echo "Query string to send is: " . $queryString . PHP_EOL;
// PHP side: this is not a real HTTP GET request, but to pretend we have
// got some data in, we'll use the same query string, parse it, and store it
// in $params
$incoming = parse_url($queryString, PHP_URL_QUERY);
parse_str($incoming, $params);
// now print contents of "phone" parameter
echo "URL parameter phone contains " . $params["phone"] . PHP_EOL;
// JSON-decode the "phone" parameter
var_dump(json_decode($params["phone"], true));
This should print:
Query string to send is: ?phone=%7B+%22phone%22%3A+%5B+%22123%22%2C+%22456%22%2C+%22789%22%5D+%7D
URL parameter phone contains { "phone": [ "123", "456", "789"] }
array(1) {
'phone' =>
array(3) {
[0] =>
string(3) "123"
[1] =>
string(3) "456"
[2] =>
string(3) "789"
}
}
which shows the JSON decodes to a proper PHP array. An array of strings, to be precise, and not numbers as requested. Turning the strings into numbers in PHP will be easy to do, but maybe you could also make sure on the call site that you send numbers and not strings.
If your original code does not work, I guess the incoming data is either no properly encoded JSON or there is some magic escaping going on (magic quotes hell, should be turned off in today's PHP, but could be a reason for garbled script input).
To make sure your JSON data is not truncated and to also save you from potential URL-encoding issues, I also suggest sending the JSON via HTTP POST, not HTTP GET.

how to remove "result": "success" on json callback

The result of the call to the api server is a json file, which begins with this string:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":[{"packWidth":250,"itemNo"
How do I remove the part that I do not care?
that is, this
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
The complete result is:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result": [{"packWidth":250,"itemNo":"1203945","groupItemNo":"1203945","status":1,"categoryId":105096,"packType":"Color Box","barcode":"6922833439687","modelLabel":"Color","packQty":24,"packInclude":"USB Cable, User Manual, USB Charger, Earphone, 1pcs Li-Battery, LCD Protector, Leather Case, Plastic Case","clearance":false,"id":103928,"packWeight":"12.500","price":"181.2800","packLength":400,"description":"description test","unitWeight":"0.726","packHeight":300}]}}
I use the PHP language
I have to remove the initial part:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
and the final:
}}
If you want to use part of a JSON to populate a CSV file, then parse the json using json_decode method and access the necessary information.
Try something like this:
var jsonObject = json_decode(myJson);
var interestingPart = jsonObject.data.result;
You can now access the data in an Object manner. Or if you want to get a json back from it, then use:
var interestingJson = json_encode(interestingPart);
Not tested, but it should work
preg_replace("/^.*?:(?=\w*\[) | (\w*}\w*}\w*$)/", "", $str);
Edit: i wrote this before I knew of json_decode, you should really use the json functions like suggested in fazovskys answer.

how to convert this json data in php

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.

Categories