how to get data in HTML using PHP?

46 views Asked by At

there is a currency conversion site at the following address:

https://www.tgju.org/currency

How can I buy prices like dollars and...?

I have a sample code that finds only one specific class using "file_get_contents" my code:

$content = file_get_contents("https://www.tgju.org/currency");
$dom = new DOMDocument();
$dom->loadHTML($content);
$finder = new DomXPath($dom);
$classname = "nf";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
$data1 = $nodes{0}->nodeValue;

Thank you for helping me to complete the code

1

There are 1 answers

3
Patrick Janser On BEST ANSWER

Looking at the HTML, I see that the US dollar row has the data-market-row attribute set to price_dollar_rl. And then all the info you want to read is then stored in some <td> cells.

So you could change your XPath query to get all these cells and then take the value of the one you desire:

<?php

$content = file_get_contents("https://www.tgju.org/currency");
$dom = new DOMDocument();
$dom->loadHTML($content) or die('Could not parse the HTML correctly!');
$finder = new DomXPath($dom);

$cells = $finder->query('//tr[@data-market-row="price_dollar_rl"]/td');

print "Found $cells->length <td> cells for US Dollar\n";
foreach ($cells as $index => $cell) {
    print "Cell n°$index: $cell->nodeValue \n";
}

// To get just the first cell:

// A) Just read item 0 from above's query.
print 'Accessing item 0: ' . $cells->item(0)->nodeValue . "\n";

// B) Change your XPath query to get the first <td> with the "nf" class.
$cells = $finder->query(
    '//tr[@data-market-row="price_dollar_rl"]//td[contains(concat(" ",normalize-space(@class)," ")," nf ")][1]'
);
print 'Accessing first td with class "nf" inside dollar row: ' . $cells->item(0)->nodeValue . "\n";

This outputs:

Found 6 <td> cells for US Dollar
Cell n°0: 490,160 
Cell n°1: (0.3%) 1,460 
Cell n°2: 489,480 
Cell n°3: 491,010 
Cell n°4: Û±Û¶:Û±Û´:Û´Û¶ 
Cell n°5:  

Accessing item 0: 490,160

Accessing first td with class "nf" inside dollar row: 490,160