Convert HTML Response to PHP Array - php

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

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

PHP: Removing white space from an unserialized entry of an array

I'm attempting to concatenate two values from a serialized array. I have this working well. The problem is one of the values Size in this case, contains white-space. I need to remove this whitespace. I have used preg_match before to remove the white-space from a variable/string. The problem I have here is how I might implement preg_match in this instance, if it is the correct approach.
foreach($contents as $item)
{
$save = array();
$item = unserialize($item);
**$item['sku'] = $item['sku'] . '' . $item['options']['Size'];**
//echo '<pre>';
//print_r($item['sku']);
//exit();
$save['contents'] = serialize($item);
$save['product_id'] = $item['id'];
$save['quantity'] = $item['quantity'];
$save['order_id'] = $id;
$this->db->insert('order_items', $save);
}
Many thanks.
PHP has function named trim() that allows trimming strings.
You can simply use str_replace like this:
$item['sku'] .= ' ' . str_replace(' ', '', $item['options']['Size']);

Add double quote between text seperated by comma [duplicate]

This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";

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

php special characters problem

I am having a problem with the special characters in my script:
This is what I have so far:
$curlstrip = explode("&", $data);
$filename = substr(htmlEntities($curlstrip[5]), 2);
and if $data contains any special charaters like ' which is ', then instead of getting the chunk of string that I need, I get only the first part.
A more detailed example:
$data = "12er&sdsretdgsd&file=Chris ' 19 &blabla"
the script will read the ' after Chris as ' and $curlstrip[5] will have a different value.
Hope is clear enough.
LE. Following this example:
$data = "12er&sdsretdgsd&file=Chris ' 19 &blabla"
$curlstrip = explode("&", $data);
$curlstrip[0] = '12er';
$curlstrip[1] = 'sdsretdgsd';
but
$curlstrip[2] = 'file=Chris' instead of 'file=Chris ' 19'
and that is because the ' is being read as
'
Thx,
Cristian.
Try:
$curlstrip = explode("&", html_entity_decode($data));
$filename = substr(htmlEntities($curlstrip[5]), 2);
As I cant replicate your error given the code supplied, I have a hunch- try:
$data=str_replace("'","'", $data);
$curlstrip = explode("&", html_entity_decode($data));
$filename = substr(htmlEntities($curlstrip[5]), 2);
If, for whatever reason, you have && (two ampersands) occurring in $data next to one another, it will interfere with the explode function.
Make htmlentities the last thing you call on the data.
$filename = htmlentities(substr($curlstrip[5], 2));
Aside from that there are functions to deal with what you're doing. parse_str will create an array from a query string. parse_url can be used to extract the query string from a url.

Categories