Google finance API - trouble fetching currency rates - php

I'm using Google's currency API to fetch exchange rates and store them in my database, but I ran into some problems. Here's what I'm working with:
http://www.google.com/ig/calculator?hl=en&q=100USD=?GBP
I'm always passing 1USD as the first parameter and exchange that to all the currencies in my database, cast the result variable as a float and store it. Everything works fine until the result from the API is greater than 1000. For example:
http://www.google.com/ig/calculator?hl=en&q=100USD=?PYG
This returns "440 528.634" as the value, and the problem is in the space delimiter. When I cast that to a float it only stores "440". I tried running str_replace() on it before i cast it to a float, but for some reason that doesn't work - I'm guessing it's not a regular whitespace but a special character of some sort. I also tried exploding the variable by a space and returning the merged array fields, but no dice. I'm running out of ideas here so I really hope someone can help me on this :D

Its a non-breaking space character. You can replace it if you refer to it as \xA0:
$result = str_replace("\xA0", "", $result);
Note the double quotes. Use those instead of single quotes as it won't work correctly otherwise.

Its NO BREAK SPACE. You should refer to it as \xA0
$x = str_replace("\xA0", "", $x);
Should work.

Related

How to get NumberFormatter::parse() to only parse actual numeric strings?

I’m trying to parse some strings in some messed-up CSV files (about 100,000 rows per file). Some columns have been squished together in some rows, and I’m trying to get them unsquished back into their proper columns. Part of the logic needed there is to find whether a substring in a given colum is numeric or not.
Non-numeric strings can be anything, including strings that happen to begin with a number; numeric strings are generally written the European way, with dots used for thousand separators and commas for decimals, so without going through a bunch of string replacements, is_numeric() won’t do the trick:
\var_dump(is_numeric('3.527,25')); // bool(FALSE)
I thought – naïvely, it transpires – that the right thing to do would be to use NumberFormatter::parse(), but it seems that function doesn’t actually check whether the string given as a whole is parseable as a numeric string at all – instead it just starts at the beginning and when it reaches a character not allowed in a numeric string, cuts off the rest.
Essentially, what I’m looking for is something that will yield this:
$formatter = new \NumberFormatter('de-DE', \NumberFormatter::DECIMAL);
\var_dump($formatter->parse('3.527,25')); // float(3527.25)
\var_dump($formatter->parse('3thisisnotanumber')); // bool(FALSE)
But all I can get is this:
$formatter = new \NumberFormatter('de-DE', \NumberFormatter::DECIMAL);
\var_dump($formatter->parse('3.527,25')); // float(3527.25)
\var_dump($formatter->parse('3thisisnotanumber')); // float(3)
I figured perhaps the problem was that the LENIENT_PARSE attribute was set to true, but setting it to false ($formatter->setAttribute(\NumberFormatter::LENIENT_PARSE, 0)) has no effect; non-numeric strings still get parsed just fine as long as they begin with a number.
Since there are so many rows and each row may have as many as ten columns that need to be validated, I’m looking at upwards of a million validations per file – for that reason, I would prefer avoiding a preg_match()-based solution, since a million regex match calls would be quite expensive.
Is there some way to tell the NumberFormatter class that you would like it to please not be lenient and only treat the string as parseable if the entire string is numeric?
You can strip all the separators and check if whatever remains is a numeric value.
function customIsNumeric(string $value): bool
{
return is_numeric(str_replace(['.', ','], '', $value));
}
Live test available here.
You can use is_numeric() to check that it is only numbers before parsing. But NumberFormatter does not do what you are looking for here.

In PHP how can i manage strings with exponential numbers

i have a problem with some alphanumeric strings containing the exponential char "E", these are stored into the db in a "character varying" column, so are strings, but when i try to visualize them in the web page i get an "INF" string instead of the original.
For example the following "55E77583" (that for me must be only a code number of an order) becomes "INF" in the webpage.
i've tried to search a solution and i found the sprintf and printf commands, but after some tries with differents %char combinations i'm not able to obtain the original form of the string.
$code = "55E77583";
echo sprintf('%s', $code);
//Gives me "INF"
$code = "55E77583";
printf('%s', $code);
//Gives me always "INF"
I really need to obtain the original form of the string, always, in all the possible alphanumeric combinations. How can i do?
Thank you.
If I understand correctly you want to display the value 55E77583 as string on your webpage. Your provided code above will exactly do that.
So somehow your variable must be converted to double or float before, this is why you receive INF because the number is too large to handle with PHP.
Make sure your variable is actually a string by echoing
echo gettype($code);
This will very likely produce "double". Maybe a type conversion is happening during your select.

Data validation on price PHP

I have the following problem. I need to validate and possibly extract currency from a value that I have received. The trouble starts with the fact that the value can be received in any encoding. Additionally to make things worse I can receive a lot of different values that should be considered correct. Let me give an example
$ 123,123,233.00
123,123.99
123.123.123,99
123.123.123 $
All of these are correct.
What I've tried is adding three arrays:
1. Chars (",","."," ")
2. Digits(0-9)
3. Currency Signs($,€...)
Trouble started when the data came in UTF-8 and I can no longer perform search digit by digit on the value I've received as in UTF-8 Currency signs are multibyte.
Question is what to do !?
I've tried the following thing.
Search for a currency sign. Then replace it with nothing. For some unknown reason PHP only replaces the second byte of the multibyte representation of the currency sign and there is a mysterious sign in the string that fails the whole check.
Any ideas are welcomed.
Datelligent idea may actually be a good simple solution: you could replace every non numerical character except the ones useful for puntuaction, with this regex \D*(?!\d{1,2}[\D$]):
$price=preg_replace('\D*(?!\d{1,2}[\D$])', '', $price);
It would transform 1233,234 234.23 into 1233234234.23.
Careful though, stuff like 123,2 34,234 would end up 123,2 34234. It does assume that punctuation followed by three or more digits isn't relevant, doesn't account for potential typos, will delete the currency symbol, etc... but it may be relevant to the scope of your issue.
Try this:
$price=$_POST['price'];
$price=preg_replace('/[^0-9]/', '', $price);
This way PHP will remove all characters and give you a string containing only numbers, which for handling prices is perfect.
If decimals are needed then modify the RegEx to get them:
$price=preg_replace('[0-9]+(\.[0-9][0-9]?)?', '', $price);

Why is str_replace() only replacing one instance of a character in a string?

I have a large string variable that is assigned from a database column of type "Text" with Collation latin_swedish_ci.
Because it is in ASCII, I need to replace all non UTF-8 characters before I can put variable into my PDF generation script.
As we all know, the standards used by PDF are evil. If I use plain ASCII input it will go insane and cause a rip in space-time.
So in order to prevent anymore damage to our universe, I need help figuring out why this str_replace() function is only replacing one of a character type and ignoring any repeats of this character
Here is my code:
$tc = str_replace (array("\n", "£", "&"), array("<br/>", "£", "&"), $tc);
Input:
Terms & Conditions: Mandatory charge of £10 for cancellations.
VAT E&EO
Output:
Terms & Conditions: Mandatory charge of £10 for cancellations.
VAT E&EO
As you can see in the output on the second line the str_replace() does not change the ampersand character.
I wonder if this is because its over two lines or something like that.
So any idea how to get the function to work as I want it to, otherwise well your going to wake up with many Micro Blackholes vanishing your bowl of cereal tomorrow.
It looks like what you are trying to achieve could be done using these 2 functions:
nl2br(htmlentities($tc));
The benefit being that if your $tc variables gets any more HTML entities in the future, you won't have to fiddle with your str_replace().

magento escape string for JavaScript part 2

This is a follow up on
magento escape string for javascript
where I accepted #AlanStorm suggestion to use json_encode to escape string literals.
But I now have a new problem with this solution.
when trying to escape a URL that has /'s in it to be rendered as a string literal for JavaScript json_encode seems to add redundant \'s in front of the /'s.
Any new suggestions here?
solutions should take a string variable and return a string that would properly be evaluated to a string literal in JavaScript. (I don't care if its surrounded with single or double quotes - although I prefer single quotes. And it must also support newlines in the string.)
Thanks
some more info: how comes '/');echo
json_encode($v); ?> results in
{"a":"\/"} ?
Details can be found here http://bugs.php.net/bug.php?id=49366
work around for this issue:
str_replace('\\/', '/', $jsonEncoded);
for your issue you can do something like
$jsonDecoded = str_replace(array("\\/", "/'s"), array("/", "/\'s"), $jsonEncoded);
Hope this helps
When I check the JSON format I see that solidi are allowed to be escaped so json_encode is in fact working correctly.
(source: json.org)
The bug link posted by satrun77 even says "It's not incorrect to escape slashes."
If you're adamant to do without and (in this case) are certain to be working with a string you can use a hack like this:
echo '["', addslashes($string), '"]';
Obviously that doesn't help for more complicated structures but as luck has it, you are using Magento which is highly modifiable. Copy lib/Zend/Json/Encoder.php to app/core/local/Zend/Json/Encoder.php (which forms an override) and fix it's _encodeString method.

Categories