2017-09-02 94 views
0

我試圖從谷歌財經retreive目前股價:在谷歌財經獲得股票價格與PHP和JSON解碼

​​

我如何可以提取只是價格(「1」)?

<?php 
$string = file_get_contents("http://finance.google.com/finance/info?client=ig&q=AAPL"); 
$json = json_decode($string, true); 
$price = $json["1"]; 
echo $price; 
?> 
+1

在你的問題中打印$ json變量 – Akintunde007

+0

...這應該回答你自己的問題 – Martijn

回答

1

的JSON返回的已被註釋掉,因此json_decode()不會做生意......你需要刪除雙斜線 - 我用explode()這樣的:

<?php 
$string = file_get_contents("http://finance.google.com/finance/info?client=ig&q=AAPL"); 
$arrMatches = explode('// ', $string); // get uncommented json string 
$arrJson = json_decode($arrMatches[1], true)[0]; // decode json 
$price = $assJson["l"]; 
echo $price; 

哦,和鍵是小寫L(l)不是數字(1)在json

+0

哦,my.dont正則表達式當你不得不。 'substr($ string,3);' – Martijn

+0

@Martijn,你可以把程序員從perl中拿出來,但是你不能把perl從程序員那裏拿出來!更新到爆炸()preg_match() –

+0

不,不要這樣。數組函數,其中簡單的字符串函數uffice也是不行的;)substr真的是你想要的 – Martijn