ob_start callback function extract output - PHP
I would like to get output "Apples", because it is inside of span tag which has id called fruit. So what codes should be written in that callback function?
<?php
function callback($buffer) {
// get the fruit inHTML text, the output should be "Apples" only
....
....
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing <span id="fruit">Apples</span> to Oranges.</p>
<开发者_开发百科;/body>
</html>
<?php
ob_end_flush();
?>
$dom = new DOMDocument;
$dom->loadHTML($buffer);
$xpath = new DOMXPath($dom);
$node = $xpath->query('//span[@id="fruit"]');
var_dump($node->item(0)->nodeValue); // string(6) "Apples"
A more generic solution...
$dom = new DOMDocument;
$dom->loadHTML($buffer);
$text = $dom->getElementsByTagName('p')->item(0)->getElementsByTagName('span')->item(0)->nodeValue;
var_dump($text); // string(6) "Apples"
精彩评论