phpjquerydomdocumentappendchildcreatetextnode

PHP createTextNode() is displaying only text using saveHTML()


I am using the following code to parse the structure of a HTML template into a DOM option, and then using results from a SQL query, I am trying to generate and append certain html fragments to a parent node of the dom object, then echo the HTML generated with styling. However, the HTML rendered is the raw HTML, and it isn't being styled.

Any ideas on what to do? I am considering moving this all to JQuery instead of PHP as after Googling I can't find a direct solution that works without doing some post processing in the HTML itself with a <script> tag.

Here is the template HTML from which nodes should be appended (jumbotron HTML):

<!-- CONTENT -->
  <div class="container">

    <div class="row">
      <!--CONTENT DIVs-->
      <div class="jumbotron col-xs-12 col-sm-10 col-sm-push-2" id="contents">

        <!--END OF CONTENT DIVs-->

And here is the PHP code:

//Create DOM of the main page
$masterdoc = new DOMDocument();
@$masterdoc->loadHTMLFile($filename);

$masterflag = $masterdoc->getElementById("contents");

//The SQL statement needed
$sql = "SELECT folder_name FROM FOLDERS INNER JOIN LINKAGES ON FOLDERS.id = LINKAGES.child WHERE folder_id = (SELECT id from FOLDERS WHERE folder_name = '" . $foldername . "');";
$result = $conn->query($sql);
$count = $result->num_rows;

//Save all the folder names into an array
$data = array();
$index = 0;
if ($count> 0) {
    while($row = $result->fetch_array()) {
        $data[$index] = $row["folder_name"];
        $index++;
    }
} else {
    echo "0 results";
}
//Loop through the array to generate Jumbotrons and append these to the right section of the main HTML.
for ($x = 0; $x <count($data); $x++) {
  $masterflag->appendChild($masterdoc->createTextNode('<div class="row"><div class="col-xs-2"><i class="fa fa-folder fa-4x"></i></div><div class="col-xs-8"><a href="http://localhost/www/folders.php?link="' . $data[$x] . '" class="btn btn-block" type="content" id="content">' . $data[$x] . '</a></div><div class="col-xs-2"><i class="fa fa-arrow-right fa-4x"></i></div></div><hr>'));
}

echo $masterdoc->saveHTML();

So that you can see what is going on, this is my page:

The text code generated


Solution

  • See this answer. You need to use DomDocument::createDocumentFragment() and then append your XML string to the created fragment and then DomElement::appendChild() that fragment to $masterflag