Reputation: 119
I am PHP newbie and I hope somebody can help.
There is a site which contains following HTML:
<span id="sell_usd_place">1.6640</span>
My code is below:
<?php
$data = file_get_contents('http://www.a_bank.com/currency-rates/');
$regex = "#<span id=\"sell_usd_place\">(.*?)</span>#";
preg_match($regex,$data,$matchKapitalSell);
var_dump($matchKapitalSell);
echo $matchKapitalSell[0]."<br>";
echo $matchKapitalSell[1];
?>
What I expect is that in the output I will get:
"<span id="sell_usd_place">1.6640</span>"
as it is what I set as a pattern.
Bit what I get is (I am using XAMPP to check the code):
array(2) { [0]=> string(39) "1.6640" [1]=> string(6) "1.6640" } 1.6640
1.6640array(0) { }
Could anybody explain please:
Why I get "1.6640" only and not
<span id="sell_usd_place">1.6640</span>
What is "39" in "string(39)" in above output?
Thank you in advance!!!
Upvotes: 1
Views: 51
Reputation: 157947
Use DOM
instead of a regex. Regular expressions aren't fitted to reliably parse HTML.
Example:
$html = file_get_contents('http://www.a_bank.com/currency-rates/');
$doc = new DOMDocument();
$doc->loadHTML($html);
$span = $doc->getElementById('sell_usd_place');
$value = $span->nodeValue;
echo $value; # 1.6640
Upvotes: 3