2011-03-17 80 views
1

我想獲得輸出「蘋果」,因爲它在span標記裏面有一個叫做水果的id。那麼應該在該回調函數中寫入哪些代碼?ob_start回調函數提取輸出 - PHP

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

回答

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" 
+0

如何刪除這個 「串(6)」,我想只有 「蘋果」。 – 2011-03-17 06:16:27

+1

大聲笑,沒關係。謝謝 :) – 2011-03-17 06:23:54