【问题标题】:How to PHP appendChild in an ID?如何 PHP appendChild 在 ID 中?
【发布时间】:2020-08-12 14:36:58
【问题描述】:
我正在尝试在我的页面中附加一个关联数组。我在here 中进行了很多搜索,但是当我尝试他们的答案时,它会复制我的页面的次数与值一样多。
这是我的代码:
$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();
}
};
如何在不增加页面的情况下做到这一点?
【问题讨论】:
标签:
php
append
appendchild
【解决方案1】:
好的,在 Pavel Musil 的帮助下,我找到了我的多次出现页面的答案:
我已将我的页面分成 3 个文件:
第一个就是:
<!DOCTYPE HTML>
<html lang="fr">
<?php
include("scores.php");
?>
</html>
第二个是PHP代码:
<?php
try {
$bdd=new PDO('mysql:host=localhost;dbname=scores','root','');
}
catch(Exception $e){
die('erreur :'.$e->getMessage());
};
$bdd->query("SET NAMES UTF8");
$reponse = $bdd->query('SELECT nom FROM `scores`');
$html = file_get_contents('tableauHtml.html');
$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();
?>
最后一个是我要插入我的 LI 的 HTML:
<head>
...
</head>
<body>
<div id='all'>
<h1>Ze Kouiz</h1>
<div id="noms">
</div>
...
</body>
它有效!
【解决方案2】:
您必须仅在创建和附加li 的部分进行循环:
$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();