2

I have this PHP code:

$document = new DOMDocument();
$document->loadHTML( $html );

$xpath = new DomXPath($document);

$tables = $xpath->query("//*[contains(@class, 'info')]");
$tableDom = new DomDocument();  
$tableDom->appendChild($tableDom->importNode($tables->item(0), true));

How can I check if the $tables variable contains something that we can work with in the $tableDom?

I tried it with:

if (!empty($tables)) {
    echo("</br>not empty</br>");
} else {
    echo("empty");
}

if (!$tablese) {
    echo("empty</br>");
}

However it always said its not empty, all trough the HTML doesn't contain a table with the class info.

0

2 Answers 2

5

try like this

if ($tables->length>0) {
    echo("</br>not empty</br>");
} else {
    echo("empty");
}
Sign up to request clarification or add additional context in comments.

Comments

0

@naga is correct. DOMXpath::query() always return an instance of DOMNodelist. (Or an error for an invalid expression).

If the expression did not match you will receive an empty list. This is an object and empty() will return false.

DOMNodeList::$length contains the number of nodes in the list. So you can validate it an condition:

if ($tables->length > 0) {

Another approach is to use foreach(). You can always iterate the node list. If you only want to use a node from a specific position (the first node) you can limit it in the Xpath expression.

$tables = $xpath->query("//*[contains(@class, 'info')][1]");
$tableDom = new DomDocument();  
foreach ($tables as $table) {
  $tableDom->appendChild($tableDom->importNode($table, true));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.