1

我想获得输出“Apples”,因为它在 span 标签内,其 id 称为fruit。那么在那个回调函数中应该写什么代码呢?

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

1 回答 1

2
$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"

更通用的解决方案...

$dom = new DOMDocument;

$dom->loadHTML($buffer);

$text = $dom->getElementsByTagName('p')->item(0)->getElementsByTagName('span')->item(0)->nodeValue;

var_dump($text); // string(6) "Apples"
于 2011-03-17T05:55:23.693 回答