Using the explode () function in Infomoney

1

I'm trying to put some economic indicators on the site and I've got a script that brings the dollar quote from the Infomoney website.

But I'm wanting other indexes, but the result of the field is composed and separated by spaces. The code looks like this:

if(!$fp=fopen("https://www.infomoney.com.br/mercados/acoes-e-indices" , "r" )) 
{
    echo "Erro ao abrir a página de indices" ;
    exit;
}
$conteudo = '';
while(!feof($fp)) 
{ 
    $conteudo .= fgets($fp,1024);
}
fclose($fp);

$valorCompraHTML    = explode('class="numbers">', $conteudo); 
// Esta é a variável que eu preciso explodir
$campo5             = trim(strip_tags($valorCompraHTML[5]));

//Estes são os valores HTML para exibir no site.    
$ibovespa = trim(strip_tags($valorCompraHTML[5]));
$ibovespa = explode(' ', $ibovespa);
$bovespa  = trim($ibovespa[0]) ;

The unexploded field looks like this: 74,294 +0.99 and the result of this variable is coming only 74,294.

I needed to know how to return the second value, +0.99

    
asked by anonymous 01.10.2017 / 21:09

3 answers

0

There are several ways to get the desired one, but I'll stick to answers that meet the difficulty posed in the question.

The value is picked up by the class="numbers positive" element

PHP

if(!$fp=fopen("https://www.infomoney.com.br/mercados/acoes-e-indices" , "r" )) 
{
    echo "Erro ao abrir a página de indices" ;
    exit;
}
$conteudo = '';
while(!feof($fp)) 
{ 
    $conteudo .= fgets($fp,1024);
}
fclose($fp);

$valorCompraHTML    = explode('class="numbers">', $conteudo); 
$ibovespa = trim(strip_tags($valorCompraHTML[5]));
$ibovespa = explode(' ', $ibovespa);
$bovespa  = trim($ibovespa[0]);

$valorMais    = explode('class="numbers positivo">', $conteudo); 
$mais = trim(strip_tags($valorMais[1]));
$mais = explode(' ', $mais);
$maisResult  = trim($mais[0]);

HTML

R$  <?php echo $bovespa  ?>  <?php echo $maisResult ?> 

Another way to get the same result

As stated in the author's question O campo sem explodir está assim: 74.294 +0,99 does not match reality, in fact the field returns like this,

Sowemustremoveallextraspacesbeforetheexplodetobethus74.294+0,99

if(!$fp=fopen("https://www.infomoney.com.br/mercados/acoes-e-indices" , "r" )) 
{
    echo "Erro ao abrir a página de indices" ;
    exit;
}
$conteudo = '';
while(!feof($fp)) 
{ 
    $conteudo .= fgets($fp,1024);
}
fclose($fp);

$valorCompraHTML    = explode('class="numbers">', $conteudo); 
// Esta é a variável que eu preciso explodir
$campo5             = trim(strip_tags($valorCompraHTML[5]));

//Estes são os valores HTML para exibir no site.    
$ibovespa = trim(strip_tags($valorCompraHTML[5]));

//retira todos os espaços em branco e retorna 74.294 +0,99
$ibovespa = preg_replace(array("/\t/", "/\s{2,}/", "/\n/", "/\r/"), array("", " ", " ", " "), $ibovespa);

$ibovespa = explode(' ', $ibovespa);

$bovespa  = trim($ibovespa[0]);

$mais  = trim($ibovespa[1]);

script for Dollar, euro etc ...

Explode () was created with the intention of separating a string into an array of several smaller strings. For this it uses certain characters, passed by parameters, to do the separation.

In programming, gambiarra is a palliative (and creative) way of solving a problem or correcting a system in an inefficient, inelegant or incomprehensible way, but it still works.

This is a code that prints the repetition of the phrase "Hello world!" 5 times using this for a loop to control

#include <stdio.h>
int main (void) {
    int i;
    for (i=0; i<5; i++) {
        printf("Hello world!");
    }
    return 0;
}

This is a code that prints on the screen the repetition of the phrase "Hello world" 5 times, but using gambiarra to obtain the final result:

#include <stdio.h>
int main (void) {
    printf("Hello world!");
    printf("Hello world!");
    printf("Hello world!");
    printf("Hello world!");
    printf("Hello world!");

    return 0;
}
    
02.10.2017 / 01:00
2

Use explode to treat and find HTML, and PHP has native features for it ... For me it's a huge gambiarra.

You can use XPath (or another resource) to find such an element directly. The number is within td with class positivo or negativo , in addition this table is inside a div with id of pnlContentA .

So it would be enough to do:

//div[contains(@id, "pnlContentA")]//td[contains(@class,"numbers") and (contains(@class, "positivo") or contains(@class, "negativo"))]

In the case of PHP:

$Numbers = $XPath->query('
//div[contains(@id, "pnlContentA")]
//td[contains(@class,"numbers") and (contains(@class, "positivo") or contains(@class, "negativo"))]
');

You can test XPath above in Chrome itself, in the console under "Elements" and then a "Ctrl + F" and pasting XPath above.

At the end it would have something like this:

libxml_use_internal_errors(true);

$ch = curl_init('http://www.infomoney.com.br/mercados/acoes-e-indices');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_FAILONERROR => 1,
    CURLOPT_PROTOCOLS => CURLPROTO_HTTP,
]);

$conteudo = curl_exec($ch); 

if($conteudo !== false) {
    $DOM = new DOMDocument();
    $DOM->loadHTML($conteudo);

    $XPath = new DOMXPath($DOM);

    $Numbers = $XPath->query('
    //div[contains(@id, "pnlContentA")]
    //td[contains(@class,"numbers") and (contains(@class, "positivo") or contains(@class, "negativo"))]
    ');

    foreach ($Numbers as $number){
        echo htmlentities($number->nodeValue, ENT_QUOTES, 'utf-8');
        echo '<br>';
    }

}

The cURL will make the request and return the body of the page, or it will fail immediately. So we created the DOM and imported the HTML, using $DOM->loadHTML($conteudo) .

Now the main part, we find the div that contains a id of pnlContentA , then find a td inside it that has the Numbers class and also has the class of positivo or negativo .

This results in:

+0,99
+1,05
+1,00
+1,67
+1,20
+1,47
+1,34
+2,12
+0,80
+1,01
+1,43
+0,97
+1,93

This site is insecure, does not have HTTPS, the connection is always redirected to HTTP. Because of this I did not make any use of any cURL feature.

    
02.10.2017 / 02:40
0

If the field is coming 74.294 +0.99 and you have created an Array with explode() :

$ibovespa = explode(' ', $ibovespa);

The elements of this Array will be:

ibovespa[0] = "74.294"
ibovespa[1] = "+0,99"

Logo , to get the second value (second Array element), just use the code:

$bovespa2  = trim($ibovespa[1]);
    
01.10.2017 / 22:01