Access a certain line of the variable

2

Some time 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 xpath documentation the description of how the nodes data is stored is not clear to my understanding.

Is there a way to access a certain nodespace without using foreach ?

    
asked by anonymous 19.01.2015 / 13:24

1 answer

2

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

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

<?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 position 0

    
19.01.2015 / 19:23