Wednesday, 25 February 2015

PHP creating a recursive DomDocument



I am attempting to create the following XML from a database table. Here is the XML



<groups>
<group id="1" name="DEBUG"/>
<group id="2" name="ORSP">
<group id="3" name="PRE">
<group id="4" name="TRANS"/>
<group id="5" name="OPP"/>
</group>
<group id="6" name="POST">
<group id="7" name="DGM"/>
</group>
</group>
</groups>


Here is the simple table to the database



GROUP_ID | GROUP_NAME | GROUP_PARENT
1 DEBUG NULL
2 ORSP NULL
3 PRE 2
4 TRANS 3
5 OPP 3
6 POST 2
7 DGM 6


Here is my current code. I am trying to return a DomElement however I can never get the above XML. Using strings I am able to produce the XML. Any advice is welcomed.



public function process(){
$xml = '<groups>';
$xml .= $this->getAllGroups();
$xml .= '</groups>';

return $xml;
}

public function getAllGroups($groupID=null){
$where = null;
$placeholder = array();
$xml = null;

if (is_null($groupID)){
$where = " GROUP_PARENT IS NULL ";
}
else {
$where = " GROUP_PARENT=?";
$placeholder=array($groupID);
}

$sql = "SELECT
GROUP_ID,
GROUP_NAME
FROM
GROUPS
WHERE
$where";
$data = $this->dbh->executeSql($sql,$placeholder);
foreach ($data["records"] as $row) {
$groupID = $row["GROUP_ID"];
$groupName = $row["GROUP_NAME"];

$xml .= "<group id='$groupID' name='$groupName'>";
$xml .= $this->getAllGroups($groupID);
$xml .= "</group>";
}
return $xml;
}

No comments:

Post a Comment