I have to parse this json data using PHP and store the values into PHP variables.
{
"sender": "[email protected]",
"receiver": "[email protected]",
"msg_id": "[email protected]",
"subject": "Group Discussion",
"references": ["[email protected]","[email protected]","[email protected]"]
}
I am using this PHP code, its not working; pls check it.
For the fields 'sender', 'receiver', 'msg_id'and 'subject, I am using PHP variables '$msg_id', '$sender', '$receiver' and '$subject'.
I am trying to store the data of 'references' in the array 'ref_id'.
Also, the file 'dataset_f.json' has content in the following way:
{ "sender":"[email protected]","receiver":"[email protected]","msg_id":"[email protected]","subject": "Project Discussion","references":["[email protected]","[email protected]","[email protected]"]}
{ "sender":"[email protected]","receiver":"[email protected]","msg_id":"[email protected]","subject": "Project Discussion","references":["[email protected]","[email protected]","[email protected]"]}
Thats why the php code is reading the file line by line
<?php
$h1 = fopen("dataset_f.json", "r");
while(!feof($h1)){
$line = fgets($h1);
$test_case = json_decode($line);
$ref_id = array();
$msg_id = $test_case->{'msg_id'};
$sender = $test_case->{'sender'};
$receiver = $test_case->{'receiver'};
$subject = $test_case->{'subject'};
foreach($test_case as $val)
{
foreach($val -> references as $refer)
{
array_push($ref_id, $refer->ref);
}
}
// printing the values
$arrlen=count($ref_id);
for($x=0;$x<$arrlen;$x++)
{ echo $ref_id[$x]." "; }
echo $msg_id." ".$sender." ".$receiver." ".$subject." <br> ";
}
?>
{[is not valid JSON (unless it's part of a string). You can't have an array for a key.