Rajib Hossain Pavel
Rajib Hossain Pavel

Reputation: 437

PHP Data Extraction in TD

This is table structure I am getting from the HTML page source-

<table id="company">              
    <tr class="alt">
        <td width="60%"><b>Trading Code:</b> BATBC</td>
        <td width="40%"><b>Scrip Code:</b> 14259</td>
    </tr>
</table>

And here is my code in PHP. Consider $HTML is the above source-

foreach($HTML->find('table[id=company]' ) as $Company){
    foreach( $Company->find('td') as $td ) {
        if( preg_match( '/Trading Code/', $td )){
            echo $td .PHP_EOL;                      
        }
        if( preg_match( '/Scrip Code/', $td )){
            echo $td .PHP_EOL;                  
        }
    }
}

My intention is to get Trading Code, BATBC and Scrip Code, 14259 but I am getting only the text parts enclosed in bold.

Upvotes: 0

Views: 44

Answers (1)

Filip Matthew
Filip Matthew

Reputation: 328

You can use regular expressions to get exactly the data from the parsed html element. I adjusted your code a little to get the data you mentioned.

foreach($HTML->find('table[id=company]' ) as $Company){
  foreach( $Company->find('td') as $td ) {
    if( preg_match( '/<b>(Trading Code|Scrip Code):<\/b> ([a-zA-Z0-9]+)/', $td, $match)){
      echo $match[1].'='.$match[2].PHP_EOL;
    }
  }
}

Upvotes: 1

Related Questions