Reputation: 23
I am trying to access information from both the first and second table on a website. Using the below code I am only able to access the first table. What syntax to I use to get to the second or the nth table?
$url = "http://iditarod.com/race/2014/";
//new dom object
$dom = new DOMDocument();
//load the html
$html = $dom->loadHTMLFile($url);
//discard white space
$dom->preserveWhiteSpace = false;
//the table by its tag name
$tables = $dom->getElementsByTagName('table');
//get all rows from the table
$rows = $tables->item(0)->getElementsByTagName('tr');
Upvotes: 2
Views: 1042
Reputation: 26415
To get the second table, use item(1)
. To get the nth table, use n - 1.
What getElementsByTagName('table')
returns is a DOMNodeList which contains all the elements named "table" in the document. The DOMNodeList method item()
returns a DOMNode from that list at the given index, with the item index starting at 0.
So to get all the rows from the second table:
$rows = $tables->item(1)->getElementsByTagName('tr');
Upvotes: 1