【问题标题】:PHP: Appending (adding) html content to exsisting element by IDPHP:通过 ID 将 html 内容附加(添加)到现有元素
【发布时间】:2015-11-18 12:23:06
【问题描述】:

我需要使用 PHP 按 ID 搜索元素,然后将 html 内容附加到它。看起来很简单,但我是 php 新手,找不到合适的函数来执行此操作。

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

我只是不知道下一步该怎么做。任何帮助将不胜感激。

【问题讨论】:

标签: php append getelementbyid


【解决方案1】:

就像 chris 在他的评论中提到的,尝试使用 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 字符串,您可以 create a document fragment 像这样:

$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 访问。

【讨论】:

    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多