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.
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
I'm trying to learn how to use JSON to store and retrieve information and I've followed several tutorials and it just isn't working the way it seems it should.
On the php page I have the following code:
<?php
$str_data = file_get_contents("test.json");
$str_decode = json_decode($str_data);
foreach($str_decode as $decoded){
echo "Report Item: " . $decoded->reportItem . "Sentences: " . $decoded-sentences;
}
?>
the JSON file has the following:
[
{
"reportItem": "gender",
"sentences": ["gender1",
"gender2",
"gender"]
},
{
"reportItem": "doctor",
"sentences": ["doctor1",
"doctor2",
"doctor3"]
},
{
"reportItem": "consent",
"sentences": ["consent1",
"consent2",
"consent3"]
}
]
If I echo the str_data after the file_get_contents it displays:
[ { "item": "gender", "sentences": ["gender1", "gender2", "gender"] }, { "item": "doctor", "sentences": ["doctor1", "doctor2", "doctor3"] }, { "item": "consent", "sentences": ["consent1", "consent2", "consent3"] } ]
Then, if I do a print_r on str_decode it displays:
Array ( [0] => stdClass Object ( [item] => gender [sentences] => Array ( [0] => gender1 [1] => gender2 [2] => gender ) ) [1] => stdClass Object ( [item] => doctor [sentences] => Array ( [0] => doctor1 [1] => doctor2 [2] => doctor3 ) ) [2] => stdClass Object ( [item] => consent [sentences] => Array ( [0] => consent1 [1] => consent2 [2] => consent3 ) ) )
However, trying to loop through the array with the foureach loop doesn't generate any output. This doesn't seem like it should be very hard and it seems to work in all the videos I've watched, but I can't get it to work. I would appreciate any help understanding what I'm missing here.
Take a look to the second argument of the json_decode function. This if it is 'true' the function returns associated array.
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
)
)
)
I'm having a real headache trying to iterate through an array and output elements. Using the array structure below I want to be able to output each instance of partname.
The following loop outputs the first instance of partname. I can't seem to adapt it to loop through all instances within the array. I'm sure I'm missing something basic.
foreach($ItemsArray['assignments'] as $item) {
$partname = $item['grades'][0]['partname'];
}
Array
(
[assignments] => Array
(
[0] => Array
(
[assigntmentid] => 5101
[grades] => Array
(
[0] => Array
(
[id] => 5101
[name] => Advanced AutoCad
[partid] => 6601
[partname] => Draft
[userid] => 82069
[grade] => 53
[courseid] => 6265
[fullname] => Computer Aided Design
)
)
)
[1] => Array
(
[assigntmentid] => 5101
[grades] => Array
(
[0] => Array
(
[id] => 5101
[name] => Advanced AutoCad
[partid] => 6602
[partname] => Final
[userid] => 82069
[grade] => 35
[courseid] => 6265
[fullname] => Computer Aided Design
)
)
)
)
)
Instead of just coding by slapping the keyboard. Write down what your function needs to do. In english (or whatever language you prefer). This would be something like:
Foreach assignment, loop over all grades and store the partname of
that grade into an array.
And then code it:
function getPartnames($assignments) {
$partNames = array();
foreach ($assignments as $assignment) {
foreach($assignment['grades'] as $grade) {
$partNames[] = $grade['partname'];
}
}
return $partNames;
}
So what did I do? I simply translated english to code.
Some few more tips: Use variables names that make sense. $item; $ItemArray; ... don't make sense. They tell me nothing
use an extra foreach in your loop:
foreach($ItemsArray['assignments'] as $item) {
foreach($item['grades'] as $grade) {
echo $grade['partname'];
}
}
I'm sorry if this is newbie question but I don't understand how to access the [ids] value in the JSON array via PHP.
Why is this not working?
$jsonResponse = json_decode($response,true);
print $jsonResponse[2]["ids"];
This is the JSON array:
Array
(
[0] => analytics#gaData
[1] => https://www.googleapis.com/analytics/v3/data/ga?ids=ga:123455&dimensions=ga:eventCategory,ga:eventAction,ga:eventLabel&metrics=ga:visits,ga:pageviews&start-date=2013-01-01&end-date=2020-01-01
[2] => Array
(
[start-date] => 2013-01-01
[end-date] => 2020-01-01
[ids] => ga:123455
[dimensions] => ga:eventCategory,ga:eventAction,ga:eventLabel
[metrics] => Array
(
[0] => ga:visits
[1] => ga:pageviews
)
[start-index] => 1
[max-results] => 1000
)
[3] => 1000
[4] => 9
There doesn't seem to be anything wrong with your code. Your code should be printing, what seems to me, the object ga:123455 if the code is executed. When printing this, this object will be converted to a string. PHP will do (string) ga:123455 (invoke the __toString() method on ga:123455) to convert an object to a string. If this method is absent, there must be a warning that ga:123455 cannot be converted to a string. __toString() might also return an empty string.
I would suggest debugging it by doing print var_dump( $jsonResponse[2]["ids"] ); and print var_dump( (string) $jsonResponse[2]["ids"] );.
I have a multi-dimensional array (There is more than one item in "data" but i'm just showing one for this question):
Array
(
[data] => Array
(
[0] => Array
(
[to] => Array
(
[data] => Array
(
[0] => Array
(
[name] => fake name
[id] => 668071477234
)
[1] => Array
(
[name] => fake name
[id] => 1345556711
)
)
)
[updated_time] => 2012-12-24T23:46:26+0000
[id] => 327424994013537
)
)
)
I am trying to loop thru the array and determine if the id matches a variable sent from $_REQUEST, and if it does, I only want to return the "updated_time" value of the iteration.
Here's what I have but the date is always wrong, and doesn't match the proper iteration:
foreach($userOutbox['data'] as $outbox){
foreach($outbox['to']['data'] as $user){
if($user['id'] == $_REQUEST['facebook_id']){
$last_message_date = $outbox['updated_time'];
}
}
}
It's late and my eyes and brain are not helping me. Can anyone give me any direction?
Here's the solution that worked for me, just added break 2; Thanks for your help:
foreach($userOutbox['data'] as $outbox){
foreach($outbox['to']['data'] as $user){
if($user['id'] == $_REQUEST['facebook_id']){
$last_message_date = $outbox['updated_time'];
break 2;
}
}
}