How can i convert this string to array? - php

I am stucked with converting the string of specific format to array. Spliting the string using explode doesn't seems to be the right approach and i am not so good with regular expressions. So my question is how can i convert the following string to array?
Current format of the string
maxWidth: 800,
openEffect: elastic,
closeEffect: elastic,
helpers : {
title : {
type: outside
},
thumbs : {
width : 50,
height : 50
}
}
Desired Array
array(
'maxWidth' => 800,
'openEffect' => 'elastic',
'closeEffect' => 'elastic',
'helpers' => array(
'title' => array('type' => 'outside'),
'thumbs' => array('width' => 50, 'height' => 50)
)
)
Any help would be greatly appreciated.
EDIT BASED ON RESPONSES:
The string looks like a JSON but it is not a JSON. Its just a string input from user in that format. The input will be from normal user so i want to keep it simple. There is minimum chance that the normal user will enter a valid JSON.

The string in your example is almost a valid JSON (JavaScript Object Notation) structure!
Here's what your string would look like as valid JSON
{
"maxWidth": 800,
"openEffect": "elastic",
"closeEffect": "elastic",
"helpers": {
"title": {
"type": "outside"
},
"thumbs": {
"width": 50,
"height": 50
}
}
}
So our approach (as suggested by #WiseGuy) would be to first inject a few characters with preg_replace to Turn your string init into valid JSON:
$str = preg_replace('/\b/' , '"' , $str);
$str = '{' . $str . '}';
The regex above is using the Word Boundaries anchor to add quotation marks around all words. Then we wrap the whole thing in curly braces and voilà, we've got a x-language compatible object format.
We can now use a standard function to produce our object:
$objUserConfig = json_decode($str, true);
A good beginners tutorial on JSON here: http://code.drewwilson.com/entry/an-introduction-to-json
Use a linter tool such as http://jsonlint.com/ to validate JSON. I used it to debug your example and convert it into proper JSON for my example.

Your input string looks like a json format. PHP has json_decode() to convert json string to object.
To convert to array, use below code:
json_decode($jsonStr, true);
Refer: http://php.net/manual/en/function.json-decode.php

Edit: I know you are showing the printed output of an array and
not a static representation of a php declared array. This is just an
example of how you might convert it into something that can be parsed
into that array. If php has that ability to do so dynamically (I don't know).
Convert the file, read in $str
In this order, do regex on $str.
Each is global flag.
(?i)([a-z]+) to '$1'
(?i)(?<=[a-z]')\s*:(?=\s*[^{\s]) to =>
(?i)(?<=[a-z]')\s*:\s*{ to => array(
} to )
Finally, $newstr = "array(\n$str\n)"
However, something like this that can be read by a php parser as a static
array. How it gets dynamically interpreted into vars I don't know.
Perl can do this.

Related

php json_encode(): "Malformed UTF-8 characters" despite no unusual characters

I have a script which creates an array containing entries for a table that I'd like to encode as json to send to my app. Each entry is an associative array of k/v pairs of string=>string|int. The code to generate the full array is as follows:
$entries = [];
foreach($stats as $i => $stat){
$playerStats = new Player_Stats($stat);
$entry = [
'place' => $i,
'name' => $playerStats->name(),
'elo' => $playerStats->currentRating(),
'highest' => $playerStats->highRating(),
'masterPoints' => $playerStats->onlineMasterPoints(),
'winLose' => $playerStats->matchesWonLost(),
'winRate' => $playerStats->winPercent(),
'numEvents' => $playerStats->numEvents(),
'wins' => $playerStats->eventsWon(),
'placed' => $playerStats->eventsPlaced()
];
$entries[] = $entry;
}
$result = json_encode($entries);
When I do a count or vardump etc on entries, It clearly shows that its been properly filled with the correct data. json_encode() returns false however. Using json_last_error_msg(), I get the UTF-8 error in the title: Malformed UTF-8 characters, possibly incorrectly encoded. All of the other posts on this issue I could find involved characters from other languages. All of the content in this array is made of the english alphabet and numbers, all ascii characters let alone utf-8.
Am I just missing something trivial (I usually am) or should I be looking for or trying something else completely?
You could use the option to ignore these, JSON_INVALID_UTF8_IGNORE so your code would be json_encode($data, JSON_INVALID_UTF8_IGNORE);
This will ignore invalid UTF-8 as the name describes. You can see all options for json_encode here. https://www.php.net/manual/en/function.json-encode.php
Something like this could do the trick:
$result = json_encode(array_map(utf8_encode, $entries))

How to get data from associative array [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
How to write PHP for get data from this.
{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}
I tried like this
$BookingDetail["room"]["single_room"];
but got result like this
Illegal string offset 'room'
and
Illegal string offset 'single_room'
How to solve it.
Try this ... you need to decode the json, you get a PHP object and then you can access each element ..
<?php
$str = '{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}';
$json = json_decode($str);
echo "<pre>";
print_r($json);
echo "</pre>";
echo $json->room->single_room;
By the way, I think your json is invalid. You can check this out at http://jsonlint.com/
The string you are using looks like JSON but it doesn't check out as valid. See JSONLint.com... Editing it to make it valid (single line)...
{"room": [{"single_room": 1, "twin_room": 3}], "total_amount": [{"amount": 20899}], "travelernum": [{"total": 1 }]}
OR (Multi-Line)...
{
"room": [{
"single_room": 1,
"twin_room": 3
}],
"total_amount": [{
"amount": 20899
}],
"travelernum": [{
"total": 1
}]
}
If this is the format all your strings are in, you can manipulate them into valid JSON by first by using...
$original_string = '{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}';
$new_string = str_replace("}{", ",", $original_string); // replace }{ with ,
Once your string is in valid JSON format, converting to a PHP array because rather simple, use something like this...
$BookingDetail = json_decode($new_string, true); //true param gets assoc array
I tested all the code above and it works.See PHP json_decode() function reference for more detail on converting JSON strings to PHP Arrays.
http://php.net/manual/en/function.json-decode.php

reformatting json using json_encode for a javascript var

quick question i really need some help, i re-formatting some json to get it into a javascript var, i got it working with json_encode but i need it to output ' symbol instead of the " symbol, is there a way to do that
i need it to be like this (using the ' symbol)
{
title:'Greeting',
mp3:'http://www.godsgypsychristianchurch.net/music/Atlanta%20GA/Dey%20duma%20amensa/01%20Greeting.mp3',
buy:'http://www.godsgypsychristianchurch.net/music/Atlanta%20GA/Dey%20duma%20amensa/01%20Greeting.mp3',
price:'Download',
duration:'',
cover:'http://godsgypsychristianchurch.net/music_artwork/DEFAULT_COVER.png'},
My Code:
foreach ($json['rows'] as $row) {
if ($_GET['churchname'] == $row[doc]['album']) {
$songCount = 0;
foreach ($row['doc']['tracks'] as $song) {
++$songCount;
$arr = array(
"title" => "{$song['name']}",
"mp3" => "{$songUrl}",
"buy" => "{$songUrl}",
"price" => "Download",
"duration" => "",
"cover" => "{$row['doc']['artwork']}",
);
echo json_encode($arr);
}
}
}
exit;
1) You can't get it to use the ' ', as the specification for valid-JSON requires " ", so any program expecting to parse your string from JSON to an object in JS/PHP/etc, is going to error out on you
2) Why? JS doesn't care which one you use, one way or another, and if you're doing something on the server-side, leave it as a multi-dimensional (potentially associative) array.
3) If it's for the purpose of including " " inside of your actual string, then escape them with \, like so:
$myString = "This is my \"double-quoted\" string";
$myString === 'This is my "double-quoted" string';
$myString === "This is my " . '"double-quoted"' . "string";
If you are concatenating strings together, and one of those strings already contains double-quotes within the string itself, then your language will automatically ensure they're escaped.
I'd be happy to help further, but I'd need to know the "Why?" part.

Parse JavaScript from remote server using curl

I need to grab a json-string from this page: https://retracted.com
If you view the source, I json-string starts after var mycarousel_itemList =. I need to parse this string as a correct json-array in my php-script.
How can this be done?
EDIT: I've managed to pull this off using explode, but the method is ugly as heck. Is there no build-in function to translate this json-string to a array?
To clarify: I want the string I grab (which is correct json) to be converted into a php-array.
The JSON in the script block is invalid and needs to be massaged a bit before it can be used in PHP's native json_decode function. Assuming you have already extracted the JSON string from the markup (make sure you exclude the semicolon at the end):
$json = <<< JSON
[ { address: 'Arnegårdsveien 32', … } ]
JSON;
var_dump(
json_decode(
str_replace(
array(
'address:',
'thumb:',
'description:',
'price:',
'id:',
'size:',
'url:',
'\''
),
array(
'"address":',
'"thumb":',
'"description":',
'"price":',
'"id":',
'"size":',
'"url":',
'"'
),
$json
)
,
true
)
);
This will then give an array of arrays of the JSON data (demo).
In other words, the properties have to be double quoted and the values need to be in double quotes as well. If you want an array of stdClass objects instead for the "{}" parts, remove the true.
You can do this either with str_replace as shown above or with a regular expression:
preg_match('
(.+var mycarousel_itemList = ([\[].+);.+function?)smU',
file_get_contents('http://bolig…'),
$match
);
$json = preg_replace(
array('( ([a-z]+)\:)sm', '((\'))'),
array('"$1":', '"'),
$match[1]
);
var_dump(json_decode($json, true));
The above code will fetch the URL, extract the JSON, fix it and convert to PHP (demo).
Once you have your json data, you can use json_decode (PHP >= 5.2) to convert it into a PHP object or array

php convert string with new lines into array?

I am getting data from an API and the resulting string is
[RESPONSE]
PROPERTY[STATUS][0]=ACTIVE
PROPERTY[REGISTRATIONEXPIRATIONDATE][0]=2012-04-04 19:48:48
DESCRIPTION=Command completed successfully
QUEUETIME=0
CODE=200
RUNTIME=0.352
QUEUETIME=0
RUNTIME=0.8
EOF
I am trying to convert this into an array like
Array(
['PROPERTY[STATUS][0]'] => ACTIVE,
['CODE'] => 200,
...
);
So I am trying to explode it using the resulting file_get_content function with an explode like
$output = explode('=',file_get_contents($url));
But the problem is the returning values are not always returned in the same order, so I need to have it like $array['CODE'] = 200, and $array['RUNTIME'] = 0.352 however there does not seem to be any kind of new line characters? I tried \r\n, \n, <br>, \r\n\r\n in the explode function to no avail. But there is new lines in both notepad and the browser.
So my question is there some way to determine if a string is on a new line or determine what the character forcing the new line is? If not is there some other way I could read this into an array?
To find out what the breaking character is, you could do this (if $data contatins the string example you've posted):
echo ord($data[strlen('[RESPONSE]')]) . PHP_EOL;
echo ord($data[strlen('[RESPONSE]')+1]); // if there's a second char
Then take a look in the ASCII table to see what it is.
EDIT: Then you could explode the data using that newly found character:
explode(ord($ascii_value), $data);
Btw, does file() return a correct array?
Explode on "\n" with double quotes so PHP understands this is a line feed and not a backslashed n ;-) then explode each item on =
Why not just use parse_ini_file() or parse_ini_string()?
It should do everything you need (build an array) in one easy step.
Try
preg_split("/$/m", $str)
or
preg_split("/$\n?/m", $str)
for the split
The lazy solution would be:
$response = strtr($response, "\r", "\n");
preg_match_all('#^(.+)=(.+)\s*$#m', $response, $parts);
$parts = array_combine($parts[1], $parts[2]);
Gives you:
Array (
[PROPERTY[STATUS][0]] => ACTIVE
[PROPERTY[REGISTRATIONEXPIRATIONDATE][0]] => 2012-04-04 19:48:48
[DESCRIPTION] => Command completed successfully
[QUEUETIME] => 0
[CODE] => 200
[RUNTIME] => 0.8

Categories