For two objects:
{"publications":[{"nom":"toto","id":"2029","userid":"22","publication":"bla bla bla","time":"2017-02-20 00:00:00","avatar":{}},{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}]}
For One object:
{"publications":{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}}
i want to have always a json array as a return no matter how the number of objects.
PHP Code:
$result = $conn->query($sql);
$json = new SimpleXMLElement('<xml/>');
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$mydata = $json->addChild('publications');
$mydata->addChild('nom',$row['nom']);
$mydata->addChild('id',$row['id']);
$mydata->addChild('userid',$row['userid']);
/*echo(utf8_encode($row['publication']));*/
$mydata->addChild('publication',utf8_encode($row['publication']));
$mydata->addChild('time',$row['time']);
$mydata->addChild('avatar',$row['avatar']);
}
echo( json_encode ($json));
} else {
echo "0";
}
asked Apr 27, 2017 at 20:21
Salim Ben Hassine
3592 gold badges7 silver badges20 bronze badges
-
2Get rid of Simplexml and use plain arrays.u_mulder– u_mulder2017年04月27日 20:25:02 +00:00Commented Apr 27, 2017 at 20:25
2 Answers 2
Well you are not using XML for anything else but convert it to JSON, so there is no need for XML. Use array
$result = $conn->query($sql);
$json = ['publications' => []];
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$json['publications'][] = [
'nom' => $row['nom'],
'id' => $row['id'],
'userid' => $row['userid'],
'publication' => $row['publication'],
'time' => $row['time'],
'avatar' => $row['avatar']
];
}
echo json_encode($json);
}
else
{
echo "0";
}
answered Apr 27, 2017 at 20:36
aprogrammer
1,7781 gold badge11 silver badges20 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
It's a particluar behaviour of SimpleXML.
If you have one child in xml - you will have an object in json, if you have more than one child - you will get array of objects. So, I advise you to rewrite your code using simple arrays instead of xml-approach:
$result = $conn->query($sql);
$json = []; // just array
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// add new item
$json[] = $row;
// or more specifically
$json[] = [
'nom' => $row['nom'],
'id' => $row['id'],
// more fields that you need
];
}
}
echo json_encode(['publications' => $json]);
answered Apr 27, 2017 at 20:31
u_mulder
54.8k5 gold badges54 silver badges72 bronze badges
Comments
lang-php