I am trying to echo a json-encoded array which consist of an array but i dont know it is not letting me print that thing. Here's my code:
<?php
include_once('confi.php');
header('Content-type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$lastRecord = isset($_POST['lastRecordID']) ?
mysql_real_escape_string($_POST['lastRecordID']) : "";
$queryForTotalRec = mysql_query("SELECT customer_id FROM `WebServiceTesting`.`sapphire` ORDER BY customer_id DESC LIMIT 1");
$total_rec = mysql_fetch_row($queryForTotalRec);
if($total_rec){
$queryForAllRecords = "SELECT * FROM `WebServiceTesting`.`sapphire` WHERE customer_ID BETWEEN %d AND %d";
$get_all_recs = mysql_query(sprintf($queryForAllRecords, $lastRecord, $total_rec[0]));
$json = array();
while($row = mysql_fetch_assoc($get_all_recs)){
$json[] = array("Status" => 1, "NewRecord" => $row);
}
print_r($json);
echo json_encode($json);
}else{
$json = array("status" => 0, "Error_Message" => mysql_error());
echo json_encode($json);
}
}else{
$json = array("status" => 0, "Error_Message" => "Request Method not correct");
echo json_encode($json);
}
#mysql_close($conn);
Errors:
Malformed JSON: Unexpected 'A' sometimes 'I'
When i am deleting the print_r line iam getting:
No response received
When i am printing the count of $json array iam getting a count of 153 but NO OTHER output.
Things i've tried:
i read in some solutions to similar problems that u need to use array_values()
for e.g:
echo json_encode(array_values($json));
same response: 'No response received'
I've also tried putting echo $json inside loop which I know that is conceptually wrong but still and got expected error 'Syntax error'
Also, i tried echoing through foreach no luck Syntax error but i can see output in raw but cannot validate the json.
Just for the info on print_r this is the response:
Array (
[0] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1241
[firstName] => Katy
[lastName] => Lest
[email] => klest#yahoo.com [phone] => 787012425
)
)
[1] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1242
[firstName] => Hanah
[lastName] => Morrisn
[email] => road#gmail.com
[phone] => 144221275 )
)
[2] => Array (
[Status] => 1 [NewRecord] => Array (
[customer_id] => 1243
[firstName] => James
[lastName] => McGrath
[email] => rosamcgrath#hotmail.com
[phone] => 79684312 )
)
)
Just found a sort of answer to this i am still looking for a reason if anyone can help in that please. The number of Records i was pulling were 150+ so i just tried with 50 records at a time and it worked perfectly. Anyone know how can i actually allocate more memory to my array so that it can hold all the required data at once only ?
I have also tried by giving accurate index as well i thought that array goes out of memory but this even not working:
$json = new SplFixedArray($difference);
Your assistance would be very much appreciated.
Stab into the dark: some of your database rows contain non-ASCII characters (e.g. ü, é and such). Your database connection is set to latin1, so the data is not UTF-8 encoded. json_encode requires UTF-8 encoded data. If you fetch enough rows, there will be rows with such non-UTF-8 data in there, and json_encode fails. With few enough rows you happen to not hit those problematic rows.
Test this by outputting echo json_last_error_msg(); after json_encode.
Set your database connection to UTF-8. See here how to do so: UTF-8 all the way through
The reason why your browser complains about invalid JSON when you include a print_r is simple: because then PHP outputs a lot of garbage which isn't JSON, which the browser can't decode as JSON.
Simply Use json_decode() you will get the result you need..
$array = json_decode($json, true);
echo "<pre>"; print_r($array);
Array
(
[0] => Array
(
[Status] => 1
[NewRecord] => Array
(
[fname] => xyz
[lname] => abc
[gender] => male
)
)
[1] => Array
(
[Status] => 1
[NewRecord] => Array
(
[fname] => 123
[lname] => 456
[gender] => male
)
)
[2] => Array
(
[Status] => 1
[NewRecord] => Array
(
[fname] => demo
[lname] => vvv
[gender] => female
)
)
)
Related
I am parsing the xml like following:
$result = '
<sms>
<status>0</status>
<message>
<contact_lists>
<contact_list><cl_id>11111</cl_id><phone>999999999</phone><name>Neu</name></contact_list>
<contact_list><cl_id>222222</cl_id><phone>888888888</phone><name>Alt</name></contact_list>
</contact_lists>
</message>
</sms>';
$xml = simplexml_load_string($result, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,true);
$contact_lists = $array['contact_lists']['contact_list'];
A sometimes the array look like this, which is works.
Array ( [status] => 0 [message] => Array ( ) [contact_lists] => Array ( [contact_list] => Array ( [0] => Array ( [cl_id] => 11111 [phone] => 999999999 [name] => Neu ) [1] => Array ( [cl_id] => 222222 [phone] => 888888888 [name] => Alt ) ) ) )
B but sometime if the array has only one contact_list, it will look like following
Array ( [status] => 0 [message] => Array ( ) [contact_lists] => Array ( [contact_list] => Array ( [cl_id] => 11111 [phone] => 999999999 [name] => Neu ) ) )
when i use $contact_listsin foreach loop it works with A since there are multiple array keys like 0,1,2,etc... but with B it shows error Warning: Illegal string offset 'name' etc.. since there are no array key like 0,1,2,etc...
so parsing the xml is automatically removing the key numbering which causing the the issue.
1- is there a way to keep the key numbering if only one array?
2- tried to use if (count($contact_lists) >= 1) { , but its not working as well..
Any idea for a workaround to solve such issue ?
SOLUTION:
$contact_lists_found = isset($array['contact_lists']['contact_list']) ? $array['contact_lists']['contact_list'] : '';
if ($contact_lists_found !== '' ) {
if (array_key_exists('0', $contact_lists_found)) {
// more than contact list
$contact_lists = $array['contact_lists']['contact_list'];
} else {
// only one contact list
$contact_lists[0] = $array['contact_lists']['contact_list'];
}
} else {
$contact_lists = array();
}
You could just check, if the key 0 is set, and if not, then simply overwrite the element contact_list with itself wrapped into an array:
if(!isset($array['message']['contact_lists']['contact_list'][0])) {
$array['message']['contact_lists']['contact_list'] = [
$array['message']['contact_lists']['contact_list']
];
}
0 is not a valid tag name in XML, so you should never get that, unless there was more than one <contact_list> in the XML.
This is my example json data
[
{"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},
{"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},
{"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},
{"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}
]
and i want to save the data to mysql with php, field product_id, price, status, name, anyone can help me please
my problem is, i dont know better code for me in php
You could use PHP
json_decode()
function to convert that json string into PHP variables.
You could then get those values and save them to the MySQL Database;
Source json_decode PHP Manual
you can use json_decode(). it takes a JSON encoded string and converts it into a PHP variable.
<?php
$json_data = '[{"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},{"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},{"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},{"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}]';
$array_data = json_decode($json_data);
echo '<pre>';
print_r($array_data);
foreach ($array_data as $event) {
echo 'Product_id:' . $event->kode;
echo "<br>";
echo 'status:' . $event->status;
echo "<br>";
}
then output is
Array
(
[0] => stdClass Object
(
[kode] => AX5
[harga] => 6200
[status] => 1
[nama] => AXIS 5
)
[1] => stdClass Object
(
[kode] => AX10
[harga] => 11250
[status] => 1
[nama] => AXIS 10
)
[2] => stdClass Object
(
[kode] => AX25
[harga] => 25750
[status] => 1
[nama] => AXIS 25
)
[3] => stdClass Object
(
[kode] => AX50
[harga] => 50800
[status] => 1
[nama] => AXIS 50
)
)
Product_id:AX5
status:1
Product_id:AX10
status:1
Product_id:AX25
status:1
Product_id:AX50
status:1
for more information
http://php.net/manual/en/function.json-decode.php
I have a JSON array object in which I am trying to append an array to one of the fields.
{"email":"bar#foo.org","password":"password","devices":{}}
print_r($arr) gives me:
Array ( [0] => {
"email":"bar#foo.org",
"password":"password",
"devices":{}
}
[1] => {
"email":"bar2#foo.org",
"password":"password",
"devices":{}
}
)
where $device_info is an array of structure:
array(
"number" => $phoneNumber,
"type" => "CellPhone",
"config" => array(
"batteryLevel" => 100,
"Lowbatterylevel" => 10,
)
I am trying to do this:
array_push($arr[$i]["devices"],$device_info);
which throws an error "Warning: Illegal string offset 'devices' "
I saw some other similar questions in StackOverflow but the solutions didn't work. Can someone point out what I'm doing wrong here? Thanks in advance.
You are not looking closely enough at your original JSON String or the full output from your print_r()
That is an Object containing properties and devices property is an object as well that contains it own properies
Here is some sample code to get your going
$s = '{"email":"bar#foo.org","password":"password","devices":{}}';
$j = json_decode($s);
$o = new stdClass();
$o->number = 999;
$o->type = "CellPhone";
$o->config = array("batteryLevel" => 100,"Lowbatterylevel" => 10);
$j->devices = $o;
print_r($j);
echo json_encode($j);
Results are
stdClass Object
(
[email] => bar#foo.org
[password] => password
[devices] => stdClass Object
(
[number] => 999
[type] => CellPhone
[config] => Array
(
[batteryLevel] => 100
[Lowbatterylevel] => 10
)
)
)
{"email":"bar#foo.org","password":"password","devices":{"number":999,"type":"CellPhone","config":{"batteryLevel":100,"Lowbatterylevel":10}}}
To me this looks like you confuse objects and arrays in your approach...
That json encoded string you posted does not encode an array but an object. So you have to treat it as such. Take a look at this simple demonstration code:
<?php
$payload = [
"number" => '01234567890',
"type" => "CellPhone",
"config" => [
"batteryLevel" => 100,
"Lowbatterylevel" => 10
]
];
$input = '{"email":"bar#foo.org","password":"password","devices":{}}';
$data = json_decode($input);
$data->devices = $payload;
$output = json_encode($data);
print_r(json_decode($output));
print_r($output);
The output ob above obviously is:
stdClass Object
(
[email] => bar#foo.org
[password] => password
[devices] => stdClass Object
(
[number] => 01234567890
[type] => CellPhone
[config] => stdClass Object
(
[batteryLevel] => 100
[Lowbatterylevel] => 10
)
)
)
{"email":"bar#foo.org","password":"password","devices":{"number":"01234567890","type":"CellPhone","config":{"batteryLevel":100,"Lowbatterylevel":10}}}
I am using json_decode on a JSON string containing unicode characters but it is not returning the desired output. I'm not sure if it is the string which contains errors or I am doing something wrong.
$test = '[{"name":"mobi7","content":"jotform test"},{"name":"city7","content":"\\u0627\\u0644\\u0625\\u0633\\u0645\\u0627\\u0639\\u064a\\u0644\\u064a\\u0629"},{"name":"sex44","content":"\\u0630\\u0643\\u0631"},{"name":"age7","content":"26"},{"name":"edu7","content":"\\u0635\\u064a\\u062f\\u0644\\u0629"}]';
print_r(json_decode($test, true));
This outputs:
Array ( [0] => Array ( [name] => mobi7 [content] => jotform test ) [1] => Array ( [name] => city7 [content] => u0627لإسماعيلية ) [2] => Array ( [name] => sex44 [content] => ذكر ) [3] => Array ( [name] => age7 [content] => 26 ) [4] => Array ( [name] => edu7 [content] => صيدلة ) )
As you can see this produces an incorrectly formatted array but I am not sure why. Any help is appreciated.
Thanks
Are you sure you're not encoding your json twice? I think those double slashes are giving you trouble:
\\u0635\\u064a\\u062f\\u0644\\u0629
I think it should look like:
$test = '[{"name":"mobi7","content":"jotform test"},{"name":"city7","content":"\u0627\u0644\u0625\u0633\u0645\u0627\u0639\u064a\u0644\u064a\u0629"},{"name":"sex44","content":"\u0630\u0643\u0631"},{"name":"age7","content":"26"},{"name":"edu7","content":"\u0635\u064a\u062f\u0644\u0629"}]';
EDIT:
Parsed result of the json above gives me the following:
[
{
"name":"mobi7",
"content":"jotform test"
},
{
"name":"city7",
"content":"الإسماعيلية"
},
{
"name":"sex44",
"content":"ذكر"
},
{
"name":"age7",
"content":"26"
},
{
"name":"edu7",
"content":"صيدلة"
}
]
Your code works ok for me adding \\ before u0627.
$json = file_get_contents('outputsjson.php');
The file encodes an array then just echoes it as this (and echo $json outputs this):
{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}
Now I'm trying to decode it from another page like this:
$myarray = json_decode($json, true);
print_r($myarray);
This outputs nothing, no errors, nothing!
Try this instead (you are mixing " and ' [single quotes instead of double quotes on the string]):
$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}} ';
$myarray = json_decode($json, true);
print_r($myarray);
And your result:
Array
(
[theList] => Array
(
[1] => Array
(
[name] => DSC04156.JPG
[title] => DSC04156.JPG
[width] => 3264
)
[2] => Array
(
[name] => DSC04157.JPG
[title] => DSC04157.JPG
[width] => 3264
)
[3] => Array
(
[name] => DSC04158.JPG
[title] => DSC04158.JPG
[width] => 3264
)
[4] => Array
(
[name] => DSC04159.JPG
[title] => DSC04159.JPG
[width] => 3264
)
)
)
Try wrapping the json string in single quotes instead of double quotes:
$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}';
I had no problems executing the following code:
$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}';
$myarray = json_decode($json, true);
print_r($myarray);
My guess would be that the file you are trying to read from does not exist. Remember that, if you are using Linux, file names are case-sensitive. Use the file_exists() function to check this:
var_dump(file_exists('outputsjson.php'));