DOMDocument::saveHTML(). php node, html. html node, node.
function getHtml($nodes) {
$result = '';
foreach ($nodes as $node) {
$result .= $node->ownerDocument->saveHtml($node);
}
return $result;
}
, Xpath. .
:
//*
id "content"
//*[@id="content"]
node, - .
//*[@id="content"][1]
- node() ,
//*[@id="content"][1]/node()
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);
echo getHtml($xpath->evaluate('//*[@id="content"][1]/node()'));
. - , . . Xpath normalize-space() . , " one two three ". , " one " . Xpath:
:
normalize-space(@class)
:
concat(" ", normalize-space(@class), " ")
,
contains(concat(" ", normalize-space(@class), " "), " title ")
//*[contains(concat(" ", normalize-space(@class), " "), " title ")][1]/node()
:
$html = <<<'HTML'
<html>
<title></title>
<body>
<h1 class="title">I am title</h1>
<div id="content">
i am the <b>content</b>.
</div>
</body>
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);
function getHtml($nodes) {
$result = '';
foreach ($nodes as $node) {
$result .= $node->ownerDocument->saveHtml($node);
}
return $result;
}
var_dump(
getHtml(
$xpath->evaluate('//*[@id="content"][1]/node()')
)
);
var_dump(
getHtml(
$xpath->evaluate(
'//*[contains(concat(" ", normalize-space(@class), " "), " title ")][1]/node()'
)
)
);
$nodes = $xpath->evaluate(
'//*[contains(concat(" ", normalize-space(@class), " "), " title ")]'
);
foreach ($nodes as $node) {
var_dump(getHtml($xpath->evaluate('node()', $node)));
}
: https://eval.in/118248
string(40) "
i am the <b>content</b>.
"
string(10) "I am title"
string(10) "I am title"