PHP: Appending (adding) html content to exsisting element by ID

后端 未结 2 1840
误落风尘
误落风尘 2021-01-05 20:34

I need to search for an element by ID using PHP then appending html content to it. It seems simple enough but I\'m new to php and can\'t find the right function to use to d

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 21:20

    Like chris mentioned in his comment try using DOMNode::appendChild, which will allow you to add a child element to your selected element and DOMDocument::createElement to actually create the element like so:

    $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);
    

    Alternatively if you already have an HTML string you want to append you can create a document fragment like so:

    $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('
    This is a test element.
    '); //actually append the element $descBox->appendChild($fragment);

    Please note that any elements added with JavaScript will be inaccessible to PHP.

提交回复
热议问题