Tengo una variable $content que contiene un fragmento de código HTML:
<b>AMZN 466.00 ( 15743 ) ( <span class='red'> -1 </span>) MSFT 290.00 ( 37296 ) ( <span class='red'> -2 </span>) TWTR 4,000.00 ( 20 ) ( <span class=''> 0 </span>)</b> Ahora, quiero los valores de <b> excluyendo los valores de <span> usando PHP DOM. ¿Cómo se puede hacer esto? Un fragmento de código sería útil.
Hasta ahora, he probado esto:
$dom = new domDocument; @$dom->loadHTML($content); $contents_i_want = $dom->getElementsByTagName('b'); foreach($contents_i_want as $content_i_want){ $filtered_content = $content_i_want->nodeValue; echo $filtered_content; }Espero que esto te ayude..
Pruebe este fragmento de código aquí
<?php ini_set('display_errors', 1); $string='<html><body><b>AMZN 466.00 ( 15743 ) ( <span class=\'red\'> -1 </span>) MSFT 290.00 ( 37296 ) ( <span class=\'red\'> -2 </span>) TWTR 4,000.00 ( 20 ) ( <span class=\'\'> 0 </span>)</b></body></html>'; $dom = new DOMDocument(); $dom->loadHTML($string); $dom->getElementsByTagName("b"); $xpath= new DOMXPath($dom); $result=$xpath->query("//b/span");//here we are querying domdocument to find span which is inside b. $nodesToRemove=array();//here we are maintaining an array of nodes which we want to remove foreach($result as $node) { $node->parentNode->removeChild($node);//removing nodes from its parent } echo $dom->getElementsByTagName("b")->item(0)->textContent;//displaying content after removing nodes.Producción:
AMZN 466.00 ( 15743 ) ( ) MSFT 290.00 ( 37296 ) ( ) TWTR 4,000.00 ( 20 ) ( )