Question

I'm using PHPQuery to read some content from HTML, I'm unable to get the element by it's index using the square bracket notation.

See this simple example:

$html = '<div><table id="theTable"><tr><td>FIRST TD</td><td>SECOND TD</td><td>THIRD TD</td></tr></table></div>';

$pq = phpQuery::newDocumentHTML($html);

$table = $pq->find('#theTable');
$tds = $table->find('td');

echo "GETTING BY INDEX:\n\n";
echo '$tds[1] = ' . $tds[1];

echo "\n\n\n";

echo "GETTING IN FOREACH:\n\n";
foreach($tds as $key => $td){
    echo '$tds[' . $key . '] = ' . pq($td) . "\n";
}

The output of this is:

GETTING BY INDEX:

$tds[1] =

GETTING IN FOREACH:

$tds[0] = FIRST TD

$tds[1] = SECOND TD

$tds[2] = THIRD TD

I would have expected that I can get the contents of $tds[1] using square brackets, but seems not. How can I get it by index?

Was it helpful?

Solution 2

Found the answer just after posting the question. Instead of square brackets you need to use eq(n):

echo '$tds[1] = ' . $tds->eq(1);

OTHER TIPS

Try a var_dump($tds), it'll tell you whats exactly inside the tds. Maybe those keys are actually strings and you should use:

echo "GETTING BY INDEX:\n\n";
echo '$tds['1'] = ' . $tds['1'];

Edit: Also, on your foreach you're using pq(), maybe you should use this

echo "GETTING BY INDEX:\n\n";
echo '$tds[1] = ' . pq($tds[1]);

Try the following:

echo '$tds[1] = ' . $tds['1'];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top