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

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

Related

Convert HTML Response to PHP Array

The response I am getting from a web call in php is something i have never seen. I have tried json_decode function and I have also tried the parse_str below, but I can't get the values to return in an array.
What i want to do is to output an array with name, price, and url. The formatting of the return has got me stumped (I copied it exactly, no typos or missing ' characters).
$urltest='https://www.***';
$result408 = file_get_contents($urltest);
//parse_str($result408, $output);
Prices = [{'name':'Seller1', 'unknown':'unknown0', 'price':60.37, 'price_f':'$60<sup style="font-size:12px;">37</sup>', 'url':'http:…'},
{'name':'Seller2', 'unknown':'unknown0','price':87.25, 'price_f':'$87<sup style="font-size:12px;">25</sup>, 'url':'http:…'},
{'name':'Seller3', 'unknown':'unknown0', 'price':74, 'price_f':'$74<sup style="font-size:12px;">00</sup>', 'url':'http:…'}];
The JSON returned from the service is bad. It looks like you can
alter it to make it into JSON that can be parsed.
Bear in mind this approach assumes that there are no single quotes
in any of the data values.
$tmp=str_replace('gSellPrices =', '',$result408);
$tmp = str_replace('"', '\"', $tmp);
$tmp = str_replace('\'', '"', $tmp);
$tmp = rtrim($tmp, '; ');
$urltest='https://www.***';
$result408 = file_get_contents($urltest);
// Remove 'Prices = '
$tmp=str_replace('gSellPrices =', '',$result408);
// Protect the existing double quotes
$tmp = str_replace('"', '\\"', $tmp);
// Now replace all the incorrect single quotes with double quotes.
$tmp = str_replace('\'', '"', $tmp);
// Remove trailing semicolon
$tmp = rtrim($tmp, '; ');
// Now we can json_decode
$data = json_decode($tmp);
Assuming that the output from service is EXACTLY as follows:
Prices = [{'name':'Seller1', 'unknown':'unknown0', 'price':60.37, 'price_f':'$60<sup style="font-size:12px;">37</sup>', 'url':'http:…'},
{'name':'Seller2', 'unknown':'unknown0','price':87.25, 'price_f':'$87<sup style="font-size:12px;">25</sup>, 'url':'http:…'},
{'name':'Seller3', 'unknown':'unknown0', 'price':74, 'price_f':'$74<sup style="font-size:12px;">00</sup>', 'url':'http:…'}];
You are looking for json_decode ( http://php.net/manual/tr/function.json-decode.php )
urltest='https://www.***';
$result408 = file_get_contents($urltest);
$output = json_decode($result408);

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.

Parameters from URL separate

i have got an URL:
http://website.example/script.php?timestamp=2014-10-31T16%3A12%3A57&sms=PM+000+name
and i want to catch values separated by '+'
if there is ability to add to array or what:
array sms[
array_value1 = PM
array_value2 = 000
array_value3 = name]
and then take value like
$name1 = $array_value3;
which will be "name"
Also if it would be done from this:
$timestamp = "2014-10-31T16%3A12%3A57";
this:
$timestamp = "2014-10-31-16:12:37";
Thanks for reply.
$foo = explode(' ', $_GET['sms']); // array('PM','000','name')
That what you're after? The + is just an encoding for a space (%20), so server-side you're looking at splitting it by spaces (though they would all fall under the same parameter).
Keep in mind if "name" turned into "name surname", you'll end up with a 4th array element containing "surname". (Array('PM','000','name','surname'))
$url=urldecode("http://website.example/script.php?timestamp=2014-10-31T16%3A12%3A57&sms=PM+0+name");
$url=parse_url($url, PHP_URL_QUERY);
$url_split = explode('&', $url);
$timestamp=$url_split[0];
$sms=explode(' ', $url_split[1]);
Close but i wanted right this:
$raw = $_GET["sms"];
list($type, $number, $user) = explode(" ", $raw, 3);
and echo $user would give result: name
Now need to do somethink with that time formatting.

Regex to convert enum field value to json

Is there a way to quickly convert simple enum data format like this
enum('one','two','three')
to json?
I wrote a code:
$res = $rst->fetch_assoc();
$type = $res['DATA_TYPE'];
$json = preg_replace('/\'/','"', $res['COLUMN_TYPE']);
$json = preg_replace("/^$type\(/",'[', $json);
$json = preg_replace('/\)/',']', $json);
return json_decode($json);
But here 3 substitutes for each part of original string: single quotes, 'enum( ' and ')'. I have read a lot about regex for converting enum but could not figure out how to do it in one leap.
replace your code with this, it should have the desired result
$res = $rst->fetch_assoc();
$type = $res['DATA_TYPE'];
preg_match_all('/\'([^\']*)\'/',$res['COLUMN_TYPE'],$matches);
return $matches[1];
you said you wanted json, but you are actually using json_decode() at the end to return an array, preg_match_all already gives you an array, so no need for decoding, if you actually want json, you could just use json_encode($matches[1])
This should work out for you.
<?php
$str = "enum('one','two','three')";
$start = strpos($str, "(")+1;
$str = substr($str, $start, strrpos($str,")") - $start);
$parts = explode(",", $str);
$enum = array_map(function($a){
return trim($a, "'");
},$parts);
return json_encode($enum);

Categories