2015-08-24 82 views
1

我需要通过使用PHP搜索元素,然后将HTML内容附加到它。它似乎很简单,但我是新来的PHP,无法找到正确的功能来使用这一点。PHP:追加(添加)HTML内容到现有的元素ID

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

我只是不知道如何做下一步。任何帮助,将不胜感激。

+2

你尝试,http://php.net/manual/en/domnode.appendchild.php?不知道'$ html'是什么,或者你想添加如此难以举例。 – chris85

回答

1

像克里斯在他的评论中提到的请尝试使用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); 

或者,如果你已经有了一个要追加可以create a document fragment像这样的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。

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

不要忘记saveHTML最后一行