Get Stock Price with PHP & JSON Decode on Google FInance - php

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

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

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

Related

PHP/MYSQL/JSON: Parse complicated string or reassemble as dictionary

I receive a complicate string through JSON that represents an object:
<Offers: 0x170483070> (entity: Offers; id: 0xd00000000b880006 <x-
coredata://03C4A684-2218-489C-9EF6-42634ED10552/Offers/p738> ; data: {\\n
topic = nil;\\n topid = 9403;\\n hasserverid = nil;\\n isprivate = nil;\\n
lasttouched = \\\"2018-07-08 16:49:01 +0000\\\";\\n lastviewed = nil;\\n
localid = 42;\\n needpicsync = nil;\\n needsync = nil;\\n secondorder
= 0;\\n oid = 0;\\n offer = test;\\n offerdone = nil;\\n offernumber =
70;\\n userid = 1;\\n wasdeleted = nil;\\n whenadded = \\\"2018-07-08
16:04:20 +0000\\\”;\\n})
I would like to save certain things to MYSQL. In the above example, I would like to save the fields offer and offernumber among others to a record with something like:
$sql = "INSERT into offers (offer,offernumber) VALUES ('test',70)";
To do this, of course, I first have to parse the string to get the value for offer, the one for offer number and ideally, the keys and values for the entire object.
Should I first convert the string into some sort of array,dictionary or data structure? Or should I try to parse the string using regex or some other method? If the latter, would appreciate suggestions on what what regex or technique to use.
Thanks in advance for any suggestions!
You can try to convert the string into a object with PHP,
this may help you:
$input = "**The input string**";
// Remove the escaped new lines
$jsonString = str_replace("\\n", "\n", substr($input, strpos($input, "data: ")+5));
$jsonString = substr($jsonString, 0, strlen($jsonString) - 1);
// Convert the equals, semicolons and remove the escaped backslash
$jsonString = str_replace(";", ",", $jsonString);
$jsonString = str_replace("=", ":", $jsonString);
$jsonString = str_replace('\\', '', $jsonString);
$matches = array();
// Use regex to get json key-value
if(preg_match_all('/(\w+)\s*\:\s*(.+)\s*\,/m', $jsonString, $matches,PREG_SET_ORDER, 0)){
// Iterate the matches and enclose key and value into double quotes
foreach($matches as $item){
// Enclose the value if isn't a number or a date
if(strpos(trim($item[2]), '"') !== 0 && !is_numeric($item[2])){
$item[2] = '"'.$item[2].'"';
}
// Replace in json string
$jsonString = str_replace($item[0], '"'.$item[1].'"'.' : '.$item[2].',', $jsonString);
}
}
// Remove last comma
$jsonString = substr($jsonString, 0, strlen($jsonString) - 3) . '}';
// Transform json string to object
$jsonObject = json_decode($jsonString);
// Show the json string
echo($jsonString);
// Display the object
var_dump($jsonObject);
the above code convert the given string to an object and then you can use the properties as you need.
you can try this here: PHP Sandbox

Extracting data from Json in Php

I have this Json Object Below, I want to extract this data and output it in PHP
{"seat_booked":"A5","0":"A5","1":"A3"}
then get them into this format
$seat_booked = "'A5', 'A5', 'A3'";
How can I do this?
I hope you are looking for this, its very simple example by using json_decode():
$string = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = json_decode($string,true);
$resuiredString = '"'."'".implode("','", $decoded)."'".'"';
echo $resuiredString;
Result:
"'A5','A5','A3'"
Side Note:
I suggest you to learn about variable concatenation.
PHP Concatenation
Another solution:
$json = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = array_map(
function($val) {
return "'". $val."'";
},
array_values(json_decode($json, true))
);
To get an object from a json in php you can use json_decode has explained here.
But you have another problem, your json is wrong!
If you want to represent a single dimensional array you should at least do this
["A5","A5","A3"]
Finally, using json_decode:
$obj = json_decode('["A5","A5","A3"]');
var_dump($obj);
Also, you could do something like:
{"0":"A5","1":"A5","2":"A3"}
$obj = json_decode('{"0":"A5","1":"A3", "2": "A5"}', true);
var_dump($obj);
Edit:
It's not very clear from your question if you are trying to get back an object from a json or if you just want to get a string from it.
If what you need is an string then you don't even need json, you could do this by string manipulation and/or using regex.
But just for completeness, if a quoted comma separated string is what you need you can do this:
$array = json_decode('["A5","A5","A3"]');
$str = implode("','",$array);
$str = "'" . $str . "'";
var_dump($str);

PHP: Convert comma separated value pair string to Array

I have comma separated value pairs and I would like to convert it to associative array in php.
Example:
{
Age:30,
Weight:80,
Height:180
}
Converted to:
Echo $obj['Weight']; // 80
Does it make a difference that my values are not in inverted commas? I mean:
Weight:80
Vs
Weight:'80'
P.S. I've posted from a phone, so I don't have a lot of fancy markup available to make this question look more presentable.
http://php.net/manual/en/function.json-decode.php
It's an JSON object which you would like to convert to an array.
$string = '{ "Age":30, "Weight":80, "Height":180 }';
$array = json_decode($string, true);
echo $array['Age']; // returns 30
Provided that the given string is a valid JSON.
UPDATE
If that doesn't work because the string doesn't contain a valid JSON object (because I see the keys are missing double quotes), you could execute this regex function first:
$string = "{ Age:30, Weight:80, Height:180 }";
$json = preg_replace('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/u', '"$1"', $string); // fix missing quotes
$obj = json_decode($json, true);
echo $obj['Age']; // returns 30
When using the regex above, make sure the string doesn't contain any quotes at all. So make sure that not some keys have quotes and some not. If so, first get rid of all quotes before executing the regex:
str_replace('"', "", $string);
str_replace("'", "", $string);
You can get all values in an array by using this basic example:
// your string
$string = "{
Age:30,
Weight:80,
Height:180
}";
// preg_match inside the {}
preg_match('/\K[^{]*(?=})/', $string, $matches);
$matchedResult = $matches[0];
$exploded = explode(",",$matchedResult); // explode with ,
$yourData = array();
foreach ($exploded as $value) {
$result = explode(':',$value); // explode with :
$yourData[$result[0]] = $result[1];
}
echo "<pre>";
print_r($yourData);
Result:
Array
(
[Age] => 30
[Weight] => 80
[Height] => 180
)
Explanation:
(?<=}) look behind asserts.
K[^{] matches the opening braces and K tells what was matched.

PHP: Extract specific word after specific word in a string?

I have a string that looks like this:
{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}
i only need the value for the country_name from that string.
so I tried this:
$country = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';
if (preg_match('#^country_name: ([^\s]+)#m', $country, $match)) {
$result = $match[1];
}
echo $result;
but there is nothing being echoed in the $result
Could someone please advise on this issue?
$country = json_decode('{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}');
echo $country->country_name;
What you have there is a JSON string.
JSON stands for JavaScript Object Notation.
PHP can decode it into an Array or Object via json_decode($string, FALSE);
The 2nd parameter by default is FALSE, which means it will convert the string into an object, which you can then access as I showed you above.
If for some reason you don't want to use JSON you can give the following a try. Note that using JSON is the recommended way doing this task.
$country = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';
$temp = explode('"country_name":', $country); //Explode initial string
$temp_country = explode(',', $temp[1]); //Get only country name
$country_name = str_replace('"', ' ', $temp_country[0]); //Remove double quotes
echo $country_name;
Result:
Ireland
Try this:
<?php
$country=json_decode('{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}')
$result=$country->country_name;
echo $result;
?>
This looks like a json string. Read more about JSON.
Use it like this:
$foo = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';
$bar = json_decode($foo, true);
echo $bar['country_name'];
This can be used with any key from that string (eg ip, city)
More about json_decode.

How do I get a value from this array that came out of json_decode?

I'm trying to use a few values from this array that comes out of json_decode, but can't get any output from var_dump (which would presumably help me figure out how to access a particular value). I've tried $data[0] also from a suggestion on a similar question.
<?PHP
$json = 'callback({"geobytesinternet":"US","geobytescountry":"United States","geobytesregionlocationcode":"USWI","geobytesregion":"Wisconsin","geobytescode":"WI","geobyteslocationcode":"USWILOLA","geobytescity":"Land O Lakes","geobytescityid":"30028","geobytesfqcn":"Land O Lakes, WI, United States","geobyteslatitude":"46.154598","geobyteslongitude":"-89.396896","geobytescapital":"Washington, DC ","geobytestimezone":"-89.3969","geobytesnationalitysingular":"American","geobytespopulation":"278058881","geobytesnationalityplural":"Americans","geobytesmapreference":"North America ","geobytescurrency":"US Dollar","geobytescurrencycode":"USD","geobytestitle":"The United States"});';
$json = str_replace( 'callback(', '', $json);
$json = str_replace( ');', '', $json);
$json = '[' . $json . ']';
$data = json_decode($json);
echo '<br>decoded: ' . $data;
echo '<br><br>var_dump: ' . var_dump($data[0]);
?>
The decoded data is object array so do something like this:
$result = $data[0];
echo $result->geobytesinternet;
You are almost there, the function json_decode() takes as input json encoded string. Your string is not properly json encoded, because of this line $json = '[' . $json . ']';.
This is properly encoded json string
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit. See the documentation.
EDIT:
So your code should look something like this:
<?php
$json = 'callback({"geobytesinternet":"US","geobytescountry":"United States","geobytesregionlocationcode":"USWI","geobytesregion":"Wisconsin","geobytescode":"WI","geobyteslocationcode":"USWILOLA","geobytescity":"Land O Lakes","geobytescityid":"30028","geobytesfqcn":"Land O Lakes, WI, United States","geobyteslatitude":"46.154598","geobyteslongitude":"-89.396896","geobytescapital":"Washington, DC ","geobytestimezone":"-89.3969","geobytesnationalitysingular":"American","geobytespopulation":"278058881","geobytesnationalityplural":"Americans","geobytesmapreference":"North America ","geobytescurrency":"US Dollar","geobytescurrencycode":"USD","geobytestitle":"The United States"});';
//Compact a bit the code, note the ');' replacement
//str_replace() can take an array of arguments, so no need to call the function multiple times
$json = str_replace( array('callback(', ');'), '', $json);
//Get elements in a array
$data = json_decode($json);
//See what's inside the array
var_dump($data);
?>
This is a working fiddle.

Categories