How to get the variation of the dollar of the website Infomoney?

Asked

Viewed 327 times

3

This code takes the purchase and sale values of the dollar and euro of the site.

I would also like to get the var(%) which is the 5th column.

See the source code and how it works by clicking here

    <?php
if(!$fp=fopen("https://www.infomoney.com.br/mercados/cambio" , "r" )) 
{
    echo "Erro ao abrir a página de cotação" ;
    exit;
}
$conteudo = '';
while(!feof($fp)) 
{ 
    $conteudo .= fgets($fp,1024);
}
fclose($fp);
$valorCompraHTML = explode('class="numbers">', $conteudo); 

$valorCompra = trim(strip_tags($valorCompraHTML[5]));

$valorVendaHTML = explode(' ', strip_tags($valorCompraHTML[6]));

//Estes são os valores HTML para exibir no site.    
$valorVendaHTML = explode(' ', $valorVendaHTML[0]);
$valorVenda  = trim($valorVendaHTML[0]) ;

//Compra Turismo.
$valorCompraT = trim(strip_tags($valorCompraHTML[7]));
$valorCompraT = explode(' ', $valorCompraT);
$valorCT  = trim($valorCompraT [0]) ;

//Venda Turismo.
$valorVendaT = trim(strip_tags($valorCompraHTML[8]));
$valorVendaT = explode(' ', $valorVendaT);
$valorVT  = trim($valorVendaT[0]) ;

//Compra Euro.
$valorCompraE = trim(strip_tags($valorCompraHTML[11]));
$valorCompraE = explode(' ', $valorCompraE);
$valorCE  = trim($valorCompraE[0]) ;

//Venda Euro.
$valorVendaE = trim(strip_tags($valorCompraHTML[12]));
$valorVendaE = explode(' ', $valorVendaE);
$valorVE  = trim($valorVendaE[0]) ;

//Estes são os valores numéricos para cálculos.   
$valorCompraCalculavel = str_replace(',','.', $valorCompra);
$valorVendaCalculavel  = str_replace(',','.', $valorVenda);
?> 
<table class="table table-bordered table-hover">
    <thead style="background: #ddd;">
        <tr>
            <td><b><center>Moeda</center></b></td>
            <td><b><center>Compra</center></b></td>
            <td><b><center>Venda</center></b></td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Dólar Comercial</td>
            <td>R$ <?php echo $valorCompra ?></td>
            <td>R$ <?php echo $valorVenda ?></td>
        </tr>
        <tr>
            <td>Dólar Turismo</td>
            <td>R$ <?php echo $valorCT ?></td>
            <td>R$ <?php echo $valorVT ?></td>
        </tr>
        <tr>
            <td>Euro</td>
            <td>R$ <?php echo $valorCE ?></td>
            <td>R$ <?php echo $valorVE ?></td>
        </tr>       
    </tbody>
</table>
  • You can put the link code in the question?

  • As well var(%) which is the 5th column?

  • Accessing the website of Infomoney you will see a table. The column Var(%) is the one that shows the percentage of variation between the previous and the current value.

  • 1

    A tip for everyone DOMXPath::query, if no one is willing to formulate a response with this, as soon as possible I will provide an example.

3 answers

3

I think it could simplify a lot and make things easier, including possible maintenance, if you use DOMXpath::query.

Note: used curl due to some certificate issues, in the new versions of PHP (5.6 and 7) it is more complicated to work with SSL (https), in the case as access has no sensitive data so I only disabled the checking of certificates:

The code should look like this:

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://www.infomoney.com.br/mercados/cambio');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);

#ignora SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_HEADER, 0);

//Define um User-agent
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');

$data = curl_exec($ch);

if($data === false) {
    die('Erro ao executar o CURL: ' . curl_error($ch));
} else {
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($httpcode !== 200) {
        die('Erro ao requisitar o servidor');
    }
}

curl_close($ch);

libxml_use_internal_errors(true);//"Não exibe os warnings" do "dom parse"

$doc = new DOMDocument;
$doc->loadHTML($data);

$xpath = new DOMXpath($doc);
$linhas = $xpath->query('//table[contains(@class, "tabelas")]//tr');

$indexados = array();

foreach ($linhas as $linha) {
    $colunas = $linha->getElementsByTagName('td');

    if ($colunas->length < 4) {
        continue;
    }

    $indexados[trim($colunas[0]->nodeValue)] = array(
        'compra' => trim($colunas[2]->nodeValue),
        'venda' => trim($colunas[3]->nodeValue),
        'variacao' => trim($colunas[4]->nodeValue),
    );
}

print_r($indexados);

It will return an Array in this format:

Array
(
    [Dólar Comercial] => Array
        (
            [compra] => 3,128
            [venda] => 3,130
            [variacao] => +0,77
        )

    [Dólar Turismo] => Array
        (
            [compra] => 3,000
            [venda] => 3,250
            [variacao] => -0,61
        )

    [Dólar PTAX800] => Array
        (
            [compra] => 3,114
            [venda] => 3,114
            [variacao] => +0,95
        )

    [Euro] => Array
        (
            [compra] => 3,749
            [venda] => 3,751
            [variacao] => +1,05
        )

    [Iene] => Array
        (
            [compra] => n/d
            [venda] => n/d
            [variacao] => 0,00
        )

    [Franco Suíço] => Array
        (
            [compra] => 3,266
            [venda] => 3,267
            [variacao] => 0,00
        )

    [Peso Argentino] => Array
        (
            [compra] => n/d
            [venda] => n/d
            [variacao] => 0,00
        )

    [Libra Esterlina] => Array
        (
            [compra] => n/d
            [venda] => n/d
            [variacao] => 0,00
        )

    [Dólar Canadense] => Array
        (
            [compra] => 2,541
            [venda] => 2,543
            [variacao] => -0,21
        )

    [Dólar Australiano] => Array
        (
            [compra] => 2,474
            [venda] => 2,476
            [variacao] => -0,76
        )

)

Which should make the job a lot easier, so you can apply it to your HTML like this:

    <tr>
        <td>Dólar Comercial</td>
        <td>R$ <?php echo $indexados['Dólar Comercial']['compra'] ?></td>
        <td>R$ <?php echo $indexados['Dólar Comercial']['venda'] ?></td>
        <td>R$ <?php echo $indexados['Dólar Comercial']['varicao'] ?></td>
    </tr>
    <tr>
        <td>Dólar Turismo</td>
        <td>R$ <?php echo $indexados['Dólar Turismo']['compra'] ?></td>
        <td>R$ <?php echo $indexados['Dólar Turismo']['venda'] ?></td>
        <td>R$ <?php echo $indexados['Dólar Turismo']['varicao'] ?></td>
    </tr>
    <tr>
        <td>Euro</td>
        <td>R$ <?php echo $indexados['Euro']['compra'] ?></td>
        <td>R$ <?php echo $indexados['Euro']['venda'] ?></td>
        <td>R$ <?php echo $indexados['Euro']['varicao'] ?></td>
    </tr>

Important note on UTF-8/Unicode

If by chance the array in print_r return problems in accents like:

Array
(
    [Dólar Comercial] => ...
    [Dólar Turismo] => ...
    [Dólar PTAX800] => ...
    [Franco Suíço] => ...
    [Dólar Canadense] => ...
    [Dólar Australiano] => ...
)

If you are using ansi/windows-1252/iso-8859-1 or compatible or even if you are using utf-8 on your page, then you will need to use utf8_decode, adjust the code for this:

foreach ($linhas as $linha) {
    $colunas = $linha->getElementsByTagName('td');

    if ($colunas->length < 4) {
        continue;
    }

   $tipo = utf8_decode(trim($colunas[0]->nodeValue));

    $indexados[$tipo] = array(
        'compra' => trim($colunas[2]->nodeValue),
        'venda' => trim($colunas[3]->nodeValue),
        'variacao' => trim($colunas[4]->nodeValue),
    );
}

print_r($indexados);
  • 1

    Top top! I never used Domxpath::query. + 1

  • @acklay xpath is something beyond PHP exists in many languages, is a handy tool :D

  • 1

    Thanks for the tip! It really seems to be very useful and by your code, it looks very simple. I’ll take a look later.

2

You can use the method explode as a parameter the line break and the first letter after the line break. See:

$variacaoHTML = strip_tags($valorCompraHTML[6]);
$variacao = explode("D", explode("\n ", $variacaoHTML, 2)[1])[0];
echo $variacao;

See working here in phpfiddle.

0

You can see in the content of the site the following object: $("tbody tr").first().children()[4]

It is the first table "body" of the first table, the 5th column, because the index is base 0.

Here’s a consult I made: inserir a descrição da imagem aqui

  • Could show an example in the code?

  • includes a picture.

  • The question is php, right? I guess jQuery won’t work for his case.

Browser other questions tagged

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