append — PHP: добавление (добавление) HTML-содержимого в существующий элемент по идентификатору

Мне нужно найти элемент по идентификатору, используя PHP, а затем добавить к нему html-контент. Это кажется достаточно простым, но я новичок в php и не могу найти подходящую функцию для этого.

$html = file_get_contents('http://example.com');
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
$descBox = $doc->getElementById('element1');

Я просто не знаю, как сделать следующий шаг. Любая помощь будет оценена.

2

Решение

Вы также можете добавить этот путь

$html = '
<html>
<body>
<ul id="one">
<li>hello</li>
<li>hello2</li>
<li>hello3</li>
<li>hello4</li>
</ul>
</body>
</html>';
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($html);
//get the element you want to append to
$descBox = $doc->getElementById('one');
//create the element to append to #element1
$appended = $doc->createElement('li', 'This is a test element.');
//actually append the element
$descBox->appendChild($appended);
echo $doc->saveHTML();

не забудьте сохранить HTML в последней строке

3

Другие решения

Как Крис, упомянутый в его комментарии, попробуйте использовать DOMNode :: AppendChild, что позволит вам добавить дочерний элемент к выбранному элементу и DOMDocument :: createElement на самом деле создать элемент так:

$html = file_get_contents('http://example.com');
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($html);
//get the element you want to append to
$descBox = $doc->getElementById('element1');
//create the element to append to #element1
$appended = $doc->createElement('div', 'This is a test element.');
//actually append the element
$descBox->appendChild($appended);

В качестве альтернативы, если у вас уже есть строка HTML, которую вы хотите добавить, вы можете добавить создать фрагмент документа вот так:

$html = file_get_contents('http://example.com');
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($html);
//get the element you want to append to
$descBox = $doc->getElementById('element1');
//create the fragment
$fragment = $doc->createDocumentFragment();
//add content to fragment
$fragment->appendXML('<div>This is a test element.</div>');
//actually append the element
$descBox->appendChild($fragment);

Обратите внимание, что любые элементы, добавленные с помощью JavaScript, будут недоступны для PHP.

1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector