1

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";
    }
1
  • 2
    Get rid of Simplexml and use plain arrays. Commented Apr 27, 2017 at 20:25

2 Answers 2

3

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";
}
Sign up to request clarification or add additional context in comments.

Comments

0

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]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.