Search code examples
phpappendappendchild

How to PHP appendChild in an ID?


I'm trying to append an associative array in my page. I searched a lot in here but when I try their answers it copies my page as many times as there are values.

Here is my code :

$reponse = $bdd->query('SELECT nom FROM `scores`');

while ($donnees=$reponse->fetch(PDO::FETCH_ASSOC)){
    foreach($donnees as $clef => $valeur){

        $html = file_get_contents('tableau.php');
        libxml_use_internal_errors(true);
        $doc = new DOMDocument();
        $doc->loadHTML($html);
        $descBox = $doc->getElementById('noms');
        $appended = $doc->createElement('li', $valeur);
        $descBox->appendChild($appended);
        echo $doc->saveHTML();

    }
};

How can I do this without my page being multiplied ?


Solution

  • You must make loop only at part where li is created and appended:

    $html = file_get_contents('tableau.php');
    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $descBox = $doc->getElementById('noms');
    
    $reponse = $bdd->query('SELECT nom FROM `scores`');
    while ($donnees=$reponse->fetch(PDO::FETCH_ASSOC)){
        foreach($donnees as $clef => $valeur){
            $appended = $doc->createElement('li', $valeur);
            $descBox->appendChild($appended);
    
        }
    }
    
    echo $doc->saveHTML();