1

I am trying to retreive the current stock price from Google Finance:

http://finance.google.com/finance/info?client=ig&q=AAPL

How can I extract just the price ("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;
?>
rainerbrunotte
  • 907
  • 1
  • 17
  • 37

2 Answers2

1

the json returned is commented out, therefore json_decode() won't do the business... you need to remove the double slashes - I used explode() like this:

<?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;

oh, and the key is a lowercase L (l) not a numeric one (1) in the json

Wee Zel
  • 1,294
  • 9
  • 11
  • oh my.dont regex when you dontr have to. `substr($string, 3);` – Martijn Sep 02 '17 at 16:06
  • @Martijn, you can take the programmer out of perl, but you can't take the perl out of a programmer! updated to explode() over preg_match() – Wee Zel Sep 02 '17 at 16:16
  • Nope, dont want that either. Array functions where simple string functions uffice is also a no go ;) substr really is the one you wanty – Martijn Sep 03 '17 at 11:26
0

The "$arrJson = json_decode($arrMatches[1], true)[0];" line doesn't work because "$arrJson" is empty after it has been executed.

Markku
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 26 '22 at 03:26