Trim number in JSON data to PHP - php

I'm trying to store the numbers from the strings on:
http://driftsdata.statnett.no//snpsrestapi/PowerData/PowerOverview/se?callback=Production.UpdateData
To my database, as these varies every hour.
However, preg_replace and str_replace doesnt work for me, as it only prints out "22" instead of "22 340" as it sais on the website.
here is my code:
for($i=0; $i<6; $i++) {
$info = get_data($countries[$i], $text);
for($j=0; $j<8; $j++) {
$info[$j] = preg_replace('/\s+/', '', $info[$j]);
$info[$j] = (int)$info[$j];
any help?

Since you are dealing with json format, the cleanest and safest way is to use json_decode():
<pre>
<?php
$jsontext = preg_replace('~^[^(]*+\(|\)$~', '', $text);
$json = json_decode($jsontext);
foreach($json->production as $prod) {
printf("<br/><strong>%s</strong><br/>%s\t%s\t%s\t%s\t%s",
$prod->type, $prod->se, $prod->dk, $prod->no, $prod->fi, $prod->ee);
$result[$prod->type] = preg_replace('~[ -]~', '',
array($prod->se, $prod->dk, $prod->no, $prod->fi, $prod->ee));
}
echo '<br/>' . print_r($result, true);
?>
</pre>

Related

php str_shuffle does wrong encoding on greek letters

I'm working on a project where I use php to grab a random greek word from a xampp sql server . I then use str_shuffle() to randomize the word order (ex. bye => ybe).However using str_shuffle() on greek letters returns the word with many ???? in place of most greek letters . If I remove str_shuffle() from my code the greek word is displayed correctly with no ??? .
I have written code that ensures I have the correct encoding but str_shuffle() is the problem .
<h1 id = "hidden-word">The word is :
<?php
$link = mysqli_connect('localhost' , 'root' , '' ,'dodecanese');
if(!$link){
echo 'Error connecting to DB';
exit;
}
mysqli_query($link,"SET NAMES 'utf8'");
$query = "SELECT island_name FROM dodecanese ORDER BY RAND() LIMIT 1";
$result = mysqli_query($link, $query);
if(!$result){
echo 'There is an issue with the DB';
exit;
}
$row = mysqli_fetch_assoc($result);
//str shuffle creates ?
echo '<span id = "random-island">'.str_shuffle($row['island_name']). '</span>';
?>
</h1>
I also have encoding <meta charset="utf-8"/> on html . I have seen many posts about this and especially the UTF-8 all the way through but it did not help . I would appreciate your help with this . Thank you in advance .
I've looked in the the PHP manual for str_shuffle and found out in the comments that indeed there are problems with some unicode chars.
But there is also a solution there - which I've tested for you, and it works:
<?php
function str_shuffle_unicode($str) {
$tmp = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
shuffle($tmp);
return join("", $tmp);
}
$a = "γκξπψ";
$b = str_shuffle($a);
$c = str_shuffle_unicode($a);
echo $a; // γκξπψ
echo "<br/>str_shuffle: ".$b; // ξ��κ�ψ�
echo "<br/>str_shuffle_unicode: ".$c; // κξγπψ
?>
Unfortunately str_shuffle() does not work with multibyte characters and there is no (or at least I do not know such) built-in function to do that. As a workaround you can write one your own. For example the below code will split the string into array of single letters, shuffle the array and then join its elements back to string (I used Cyrillic letters for the example):
$str = "абвгдежзий";
$temp = mb_str_split($str,1);
shuffle($temp);
$str = join("", $temp);
echo $str;
The above function mb_str_split is a PHP 7.4+ only. If you are using earlier version, you can use preg_split:
$str = "абвгдежзий";
$temp = preg_split("//u", $str, 0);
shuffle($temp);
$str = join("", $temp);
echo $str;
the more uncomfortable preg_match_all:
$str = "абвгдежзий";
preg_match_all('/./u', $str, $temp);
shuffle($temp[0]);
$str = join("", $temp[0]);
echo $str;
or even looping and adding to the array char-by-char (that way you save a regex call):
$str = "абвгдежзий";
$len = mb_strlen($str, 'UTF-8');
$temp = [];
for ($i = 0; $i < $len; $i++) {
$temp[] = mb_substr($str, $i, 1, 'UTF-8');
}
shuffle($temp);
$str = join("", $temp);
echo $str;

Result is different when use base64_decode with php

I have some problem with base64 encode and decode, I would like to decode my string with php, I have found a solution but it's not work well, My expectation I would like decode only string which have been encode and other string which is not encoded should keep normal.
Here is a string :
$string = "I need your help 4Z6B4Z+S4Z6b4Z624Z+G4Z6E4oCL4Z6O4Z624Z6f4Z+L4oCL";
Here is what I have tried :
echo base64_decode($string);
Result:
SSBuZWVkIHlvdXIgaGVscA = ខ្លាំង​ណាស់​
The result above is not what I need, below is what I need:
I need your help ខ្លាំង​ណាស់​
So, could anyone tell me how to do it with php.
This should work for you:
<?php
$str = "I need your help 4Z6B4Z+S4Z6b4Z624Z+G4Z6E4oCL4Z6O4Z624Z6f4Z+L4oCL";
for($count = 0; $count < strlen($str); $count++) {
$temp = substr($str, $count, strlen($str));
if ( base64_encode(base64_decode($temp, true)) === $temp) {
echo substr($str, 0, $count) . base64_decode($str);
break;
}
}
?>

Fastest way to retrieve part from JSON in my case

Now, I use strstr to get data from external JSON file. I'm not sure if it's the fastest way to do that what I want and I can't test because json_decode don't work in my code.
$before = '"THIS":"';
$after = '","date"';
$data = strstr(substr($url, strpos($url, $before) + strlen($before)), $after, true)
and with json_decode:
$address = file_get_contents('http://json.link/?something=Hello');
$data = json_decode($address);
echo $data->data->THIS;
Now, when I replace my first code with second I get:
Notice: Trying to get property of non-object
All my code:
$text = "a lot of text";
$text_split = array(0 => '');
$number = 0;
$words = explode(' ', $text);
foreach($words as $word)
{
if(strlen($text_split[$number]) + strlen($word) + 1 > 500)
{
++$number;
$text_split[$number] = '';
}
$text_split[$number] .= $word.' ';
}
foreach($text_split as $texts)
{
$text_encode = rawurlencode($texts);
$address = file_get_contents('http://json.link/?something='.$text_encode);
$data = json_decode($address);
echo $data->data->THIS;
}
What should in do in that case? Keep using strstr or replace all code to work with json_decode (maybe because execution time is faster?)? If the second option, how I can make json_decode work here? Thanks!
... and sorry for bad english.
LE:
If I replace $address = file_get_contents('http://json.link/?something='.$text_encode); with $address = file_get_contents('http://json.link/?something=Hello'); I get VALID result for "Hello" text but 10 times. I guess because it's in a foreach.
json_decode is the suggested method to work with JSON data. Here I think you are trying to access an invalid property in JSON object.
$data = json_decode($address);
echo $data->data->THIS;
I guess you need $data->date instead of $data-data?
you have to access the specific key value like this
$json = '{"success":true,"msg":"success","data":{"THIS":"thing I need","date":"24.03.2014","https":false}}';
$d=json_decode($json,true);
echo $d['data']['THIS'];

Encode the url including hyphen(-) and dot(.) in php

I need the encoded URL for processing in one of the API, but it requires the full encoded URL. For example, the URL from:
http://test.site-raj.co/999999?lpp=1&px2=IjN
has to become an encoded URL, like:
http%3a%2f%test%site%2draj%2eco%2f999999%3flpp%3d1%26px2%3dIjN
I need every symbol to be encoded, even the dot(.) and hyphen(-) like above.
Try this. Inside a function maybe if you are using it more than once...
$str = 'http://test.site.co/999999?lpp=1&p---x2=IjN';
$str = urlencode($str);
$str = str_replace('.', '%2E', $str);
$str = str_replace('-', '%2D', $str);
echo $str;
This will encode all characters that are not plain letters or numbers. You can still decode this with the standard urldecode or rawurldecode:
function urlencodeall($x) {
$out = '';
for ($i = 0; isset($x[$i]); $i++) {
$c = $x[$i];
if (!ctype_alnum($c)) $c = '%' . sprintf('%02X', ord($c));
$out .= $c;
}
return $out;
}
Why don't you use rawurlencode
for example rawurlencode("http://test.site-raj.co/999999?lpp=1&px2=IjN")

Indexed substitution within string

I am looking to convert a string with a special HTML tag and parse it accordingly. Below I will show what the original string is followed by what I want the parsed string to be. If someone can direct me towards a proper coding method to make this possible that would be fantastic.
Original String:
$string = '<string 1="Jacob" 2="ice cream">{1} likes to have a lot of {2}.</string>';
Parsed String:
$parsed_string = 'Jacob likes to have a lot of ice cream.';]
EDIT:
I forgot to add that the $string variable may having multiple strings with multiple options, for example the $string variable could be the following:
$string = '<string 1="hot dog">I like to have {1}</string> on <string 1="beach" 2="sun">the {1} with the blazing hot {2} staring down at me.';
I need a solution that can parse the code example above.
EDIT 2:
Here is a sample code I developed that is incomplete and has a few bugs. If there is more than one option e.x. 1='blah' 2='blahblah' it will not parse the second option.
$string = '<phrase 1="Jacob" 2="cool">{1} is {2}</phrase> when <phrase 1="John" 2="Chris">{1} and {2} are around.</phrase>';
preg_match_all('/<phrase ([0-9])="(.*?)">(.*?)<\/phrase>/', $string, $matches);
print $matches[1][0] . '<br />';
print $matches[2][0] . '<br />';
print $matches[3][0] . '<br />';
print '<hr />';
$string = $matches[3][0];
print str_replace('{' . $matches[1][0] . '}', $matches[2][0], $output);
print '<hr />';
print '<pre>';
print_r($matches);
print '</pre>';
As $string is no valid XML (e.g. containing numbers as attribute names), you may try:
$string = '<string 1="Jacob" 2="ice cream">{1} likes to have a lot of {2}.</string>';
$parsed_string = strip_tags($string);
for ($i = 1; $i <= 2; $i++) {
if (preg_match('/' . $i . '="([^"]+)"/', $string, $match))
$parsed_string = str_replace('{' . $i .'}', $match[1], $parsed_string);
}
echo $parsed_string;
UPDATE
Your EDIT switched from having one <string> tag to having multiple <string> tags in the variable now. This one should work for multiples:
$string2 = '<string 1="hot dog">I like to have {1}</string> on <string 1="beach" 2="sun">the {1} with the blazing hot {2} staring down at me.</string>';
$parsed_string2 = '';
$a = explode('</string>', $string2);
foreach ($a as $s) {
$parsed_elm = strip_tags($s);
for ($i = 1; $i <= 2; $i++) {
if (preg_match('/' . $i . '="([^"]+)"/', $s, $match))
$parsed_elm = str_replace('{' . $i .'}', $match[1], $parsed_elm);
}
$parsed_string2 .= $parsed_elm;
}
echo $parsed_string2;
<?php
$rows = array();
$xml = "
<string 1="Jacob" 2="ice cream">{1} likes to have a lot of {2}.</string>
<string 1="John" 2="cream">{1} likes to have a lot of {2}.</string>
"
$parser = xml_parser_create();
xml_parse_into_struct($parser, trim($xml), $xml_values);
foreach ($xml_values as $row){
$finalRow = $row['values'];
foreach ($row['attributes'] as $att => $attval){
$finalRow = str_replace ($finalRow, "{".$att."}", $attval);
}
$rows[] = $finalRow;
}
?>
Here's a version that doesn't use regex, this seemed more straight forward. I don't know how the xml parser would cope with attributes that start with a number though.

Categories