0

first of all I know that there are many topics about this, but I did not find a solution in any of them. My problem is the following, I want to extract with php using "file_get_contents" 2 data from a site that have the same name in the div. I need to extract the data and then assign each one a certain variable with PHP. Anyway, here is the code snippet that does NOT return anything.

$htmlOficial = file_get_contents('https://www.dolarhoy.com/cotizaciondolaroficial');
preg_match('/<tr><td><a href="#">Banco Nacion</a></td><td class="number">(.*)</td>/', 
$htmlOficial, $ventaOficial);
preg_match('/<tr><td><a href="#">Banco Nacion</a></td><td class="number"></td> <td class="number">(.*)</td>
            </tr>/', 
$htmlOficial, $compraOficial);
$ventaOficial = $ventaOficial[1];
$compraOficial = $compraOficial[1];

The site is https://www.dolarhoy.com/cotizaciondolaroficial, In the "entities" box it says "Banco Nacion". I need to extract the data of "buy" on the one hand and "sale" on the other

tomas
  • 41
  • 1
  • 7
  • One space in the regex won't match multiple spaces and linebreaks. Easier options, btw: DOM traversal (sometimes, though not here), or strip_tags() and matching just the text snippets. – mario Jun 17 '20 at 03:31

1 Answers1

0

Successfully tested now. Sometimes simpler is better. Divide and conquer, use explode and a function to grab a string from text that is between two other strings (in your case you want the contents of table column with "number" class and the close column tag (td)).

$htmlOficial = file_get_contents('https://www.dolarhoy.com/cotizaciondolaroficial');

$chunk = strbtw($htmlOficial, 'Banco Nacion', '</tr>');
$number_chunks = explode('class="number"', $chunk);
$ventaOficial = strbtw($number_chunks[1], '>', '</td>');
$compraOficial = strbtw($number_chunks[2], '>', '</td>');

echo "ventaOficial[{$ventaOficial}]<br/>";
echo "compraOficial[{$compraOficial}]<br/>";

function strbtw($text, $str1, $str2="", $trim=true) {
    $len = strlen($str1);
    $pos_str1 = strpos($text, $str1);
    if ($pos_str1 === false) return "";
    $pos_str1+=$len;

    if (empty($str2)) { // try to search up to the end of line
        $pos_str2 = strpos($text, "\n", $pos_str1);
        if ($pos_str2 === false) $pos_str2 = strpos($text, "\r\n", $pos_str1);
    }
    else $pos_str2 = strpos($text, $str2, $pos_str1);

    if ($pos_str2 !== false) {
        if ($pos_str2-$pos_str1 === 0) $rez = substr($text, $pos_str1);
        else $rez = substr($text, $pos_str1, $pos_str2-$pos_str1);
    }
    else $rez = substr($text, $pos_str1);

    return ($trim) ? trim($rez) : ($rez);
}

Please let me know if it works.

Juanga Covas
  • 315
  • 2
  • 5