Tom C
Tom C

Reputation: 842

Trying to traverse the HTML DOM structure using PHP?

$p = new DOMDocument();
echo $data;
$static = $p->loadHTML($data);
$static = $static->getElementByTagName("html")->item(0);
$static = $static->getElementByTagName("body")->item(0);
$static = $static->getElementByTagName("table")->item(0);
$static = $static->getElementByTagName("tr")->item(0);
$static = $static->getElementByTagName("td")->item(0);
$static = $static->getElementByTagName("table")->item(0);
$static = $static->getElementByTagName("tr")->item(5);
$static = $static->getElementByTagName("td")->item(1);
$static = $static->getElementByTagName("div")->item(0);
$static = $static->getElementByTagName("table")->item(0);
$static = $static->getElementByTagName("tr")->item(0);
$static = $static->getElementByTagName("td")->item(0);
$static = $static->etElementByTagName("center")->item(0);
echo $static;

Thats my code above, im not sure if I am doing it correctly but it seems like its right (Im trying to basically go through the structure to find the exact part I need). However I keep getting this error:

Fatal error: Call to a member function getElementByTagName() on a non-object in blah on line 18

(Line 18 being the first "getElementByTagName")

I also get these errors if its anything to do with it:

Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: Opening and ending tag mismatch: td and center in Entity, line: 83 in on line 17

Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: Opening and ending tag mismatch: td and center in Entity, line: 83 in on line 17

Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: Opening and ending tag mismatch: td and center in Entity, line: 87 in on line 17

Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: Unexpected end tag : div in Entity, line: 91 in on line 17

but yeah, can anyone help please?

Upvotes: 0

Views: 5357

Answers (3)

David
David

Reputation: 46

You have mistyped the function name as getElementByTagName. The correct function name is getElementsByTagName. When I repeated your code with this correction it worked properly.

Upvotes: 3

Igor Parra
Igor Parra

Reputation: 10348

For the record:

Sometimes we can't fix malformed documents.
We can block those warnings with the @ (error control) operator.

$static = @$p->loadHTML($data);

Upvotes: 3

meder omuraliev
meder omuraliev

Reputation: 186552

First, fix your HTML so it's valid per those errors. Then do DOM processing.

You can also use DOMXpath and do

->evaluate('/body/table/tr/td/table/tr/td/div/table/tr/td/center')

Or you can just do ->evaluate('//center') and grab all center elements.

after you get your HTML valid. You can also give that center element an id. Ideally, you should never use the center element though.

Upvotes: 5

Related Questions