1

果物というIDを持つスパンタグの中にあるので、出力「りんご」を取得したいと思います。では、そのコールバック関数にはどのようなコードを記述すればよいのでしょうか?

 <?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 に答える