How to get the dollar variation of infomoney site?

4

This code picks up the dollar and euro values 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>
    
asked by anonymous 12.09.2017 / 19:41

3 answers

2

You can use the explode method as a parameter to break the line 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 .

    
12.09.2017 / 21:58
2

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

  

Note: I used curl because of some certificate issues, in new versions of PHP (5.6 and 7) it is more complicated to work with SSL ( https ), does not have sensitive data so I just disabled checking the 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
        )

)

What should make work much 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 about UTF-8 / Unicode

If the array does not print_r return problems in accents such as:

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 using utf-8 on your page, then you will need to use utf8_decode , set the code to 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);
    
12.09.2017 / 22:33
0

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

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

Here is the query I did:

    
12.09.2017 / 20:34