Access certain line of the variable

Asked

Viewed 102 times

2

A while ago I asked a question about regular expressions and a user answered me using this code, using xpath:

$dom = new DomDocument;
$dom->loadHTMLFile("http://ciagri.iea.sp.gov.br/precosdiarios/");

$xpath = new DomXPath($dom);
// essa query pega o todos os TDs na posicao 3 da primeira tabela com a classe  
$nodes = $xpath->query("(//table[@class='tabela_dados'])[1]/tr/td[position()=3]");

foreach ($nodes as $i => $node) {
    echo $node->nodeValue . "\n"; // vai imprimir todos os preços
}

In the documentation of xpath the description of how the data of the "nodes" are stored has not become clear to my understanding.

There is a way to access a certain space of the "nodes" without the use of the foreach?

1 answer

2


The return of the method query() of the object DomXPath is an object of the type DOMNodeList.

You can access the items in this list through the method item():

<?php

$dom = new DomDocument;
$dom->loadHTMLFile("http://ciagri.iea.sp.gov.br/precosdiarios/");

$xpath = new DomXPath($dom);

// Estava faltando um "tbody" antes do "tr"
$nodes = $xpath->query("(//table[@class='tabela_dados'])[1]/tbody/tr/td[position()=3]");

// Na pagina que você está carregando existem espaços em branco
// dentro das células pesquisadas. Nesse caso usei o trim pra limpá-los
echo trim($nodes->item(8)->nodeValue);

Note that the list of DOMNodeList starts with the position 0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.