1

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();
    ?>
Sally Hammel
  • 194
  • 1
  • 8

1 Answers1

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"

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"
alex
  • 479,566
  • 201
  • 878
  • 984