简体   繁体   中英

How to get href value and a th value from a table at the same time

I am having one table with many <tr> tags. In each <tr> , there are 4 <td> tags. In the 1st td , i am having one <a> tag, now I need to store the href value and the 3rd <td> value in an array.

Here is my code

      <tr> 
          <td><a href="http://www.example.com">Some name</a></td>
          <td>2009</td>
          <td>United States</td>
          <td> abc, xyz</td>
      </tr>
       ---------------------
       ---------------------

      <tr> 
          <td><a href="http://www.example10.com">Some name</a></td>
          <td>2010</td>
          <td>India</td>
          <td> abc, xyz</td>
      </tr>

Now, I am collecting all the href values, I dont know how to get the 3rd td value and store in the array at the same time. My code for collecting href's is

        $d = new DOMDocument();
        @$d->loadHTML( $contents );
        $a = $d->getElementsByTagName("a");
        $i = 0;
        foreach ( $a as $element ) {
           $element->getAttribute('href');
        }

Please help me in this. Thanks in advance!

Basically

$dom = new DOMDocument();
@$dom->loadHTML( $contents );
//get 1 table only
$node = $dom->getElementsByTagName("table")->item(0);
//$nodeA = $node->getElementsByTagName('a');
$nodeTr = $node->getElementsByTagName('tr')->item(2)

//foreach ( $nodeA as $element ) {

      //echo $element->getAttribute('href');
//}
echo $nodeTr->nodeName,':', $nodeTr->nodeValue;

use this into ur foreach loop

alert(document.getElementsByTagName("td")[2].innerHTML);

O/P : United States,India all details which is in 3rd TD

Thanks all for the suggestions. I got the expected output finally.

        $d = new DOMDocument();
        $d->validateOnParse = true;
        @$d->loadHTML($contents);
        $xpath = new DOMXPath($d);
        $table = $xpath->query("//table/tr");
        foreach ($table as $row) {
         $a_val = $row -> getElementsByTagName('a')->item(0)->getAttribute('href');;
         $td_val = $row -> getElementsByTagName('td')->item(2)->nodeValue;
         $data.= "{$a_val} - {$td_val}\n";  
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM