0
我想用DOMDocument類來操縱一些HTML數據,但它看起來沒有像預期的那樣工作。DOMDocument沒有將HTML標籤寫入DOMNodes
$html_str = <<< 'EOD'
<h1>Hello world</h1>
<p>This is the first paragraph</p>
<p>Now for a second</p>
<p>This is the last</p>
EOD;
$html_doc = new DOMDocument();
$html_doc->loadHTML($html_str); //loadHTML wraps code in html and body nodes
$body_node = $html_doc->getElementsByTagName('body')->item(0); //Select body node which is holding loaded html data
echo $html_doc->saveHTML($body_node);
//Outputs as expected
//<body>
//<h1>Hello world</h1>
//<p>This is the first paragraph</p>
//<p>Now for a second</p>
//<p>This is the last</p>
//</body>
echo count($body_node->childNodes);
//Outputs only 1
echo $html_doc->saveHTML($body_node->childNodes->item(0));
//Outputs
//<h1>Hello world</h1>
爲什麼我加載的HTML數據不能識別爲單個節點。我希望能夠操縱身體標記內的每個節點,但正如您所看到的,我無法使用cildeNodes屬性來定位它們。