I receive string "{success: false, errors: { reason: 'text text text' }}" by CURL, how to convert this string to array or object?
String '{"success": "false"....}' may be converted to object by json_decode, but I have string without qoutes.
Use this regex first (it adds quotes)
$json = preg_replace ('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/u', '"$1"', $string);
After that, you can simply use json_decode()
$array = json_decode ($json);
Update
I found this script somewhere:
function json_fix_quotes ($string){
$string = str_replace("{",'{"',$string);
$string = str_replace(":'",'":"',$string);
$string = str_replace("',",'","',$string);
$string = str_replace("'}",'"}',$string);
return $string;
}
Try that instead of the regex
Related
I need save $GLOBALS into a field in MySQL, but...
$GLOBALS is an ARRAY
When I try with some function as
function array_to_string($array){
$string = '';
code...
$string .= code...
code...
return $string;
}
$string = array_to_string($GLOBALS);
this "$string" grow and grow... (is infinite)
Any idea please?
you can try implode() function....
The implode() function returns a string from the elements of an array.
For example..
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
the output
Hello World! Beautiful Day!
Conversion to JSON is adviced.
$string=json_encode($array);
json_encode Returns a JSON encoded string on success or FALSE on failure.
$array_back=json_decode($string);
json_decode Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
Try to use utf8_encode and json_encode
$arr = array_map('utf8_encode', $arr);
$json = json_encode($arr);
I have this string saved in $metaV:
{"feedName":"Paypal Test","paypalEmail":"managercvtech#gmail.com","mode":"test","transactionType":"subscription","recurringAmount":"form_total","billingCycle_length":"1","billingCycle_unit":"day","recurringTimes":"0","recurringRetry":"0","trial_enabled":"1","trial_product":"73","trial_amount":"","trialPeriod_length":"1","trialPeriod_unit":"month","billingInformation_firstName":"4","billingInformation_lastName":"27","billingInformation_email":"5","billingInformation_address":"","billingInformation_address2":"","billingInformation_city":"","billingInformation_state":"","billingInformation_zip":"34","billingInformation_country":"","pageStyle":"","continueText":"","cancelUrl":"","disableShipping":"0","disableNote":"0","delayNotification":"0","selectedNotifications":"","feed_condition_conditional_logic":"0","feed_condition_conditional_logic_object":{"conditionalLogic":{"actionType":"show","logicType":"all","rules":[{"fieldId":"73","operator":"is","value":"1 month"}]}},"type":"subscription","recurring_amount_field":"form_total","update_user_action":"","delay_registration":"","update_site_action":""}
I want to replace this part of the string:
"trial_enabled":"0"
I tried to use str_replace() for this:
str_replace('\"trial_enabled\":\"1\"', '\"trial_enabled\":\"0\"',$metaV);
You could use json_decode and json_encode to transform your string into an array and the way back.
$data = json_decode($metaV, true);
$data['trial_enabled'] = "1";
$metaV = json_encode($data);
I have this Json Object Below, I want to extract this data and output it in PHP
{"seat_booked":"A5","0":"A5","1":"A3"}
then get them into this format
$seat_booked = "'A5', 'A5', 'A3'";
How can I do this?
I hope you are looking for this, its very simple example by using json_decode():
$string = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = json_decode($string,true);
$resuiredString = '"'."'".implode("','", $decoded)."'".'"';
echo $resuiredString;
Result:
"'A5','A5','A3'"
Side Note:
I suggest you to learn about variable concatenation.
PHP Concatenation
Another solution:
$json = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = array_map(
function($val) {
return "'". $val."'";
},
array_values(json_decode($json, true))
);
To get an object from a json in php you can use json_decode has explained here.
But you have another problem, your json is wrong!
If you want to represent a single dimensional array you should at least do this
["A5","A5","A3"]
Finally, using json_decode:
$obj = json_decode('["A5","A5","A3"]');
var_dump($obj);
Also, you could do something like:
{"0":"A5","1":"A5","2":"A3"}
$obj = json_decode('{"0":"A5","1":"A3", "2": "A5"}', true);
var_dump($obj);
Edit:
It's not very clear from your question if you are trying to get back an object from a json or if you just want to get a string from it.
If what you need is an string then you don't even need json, you could do this by string manipulation and/or using regex.
But just for completeness, if a quoted comma separated string is what you need you can do this:
$array = json_decode('["A5","A5","A3"]');
$str = implode("','",$array);
$str = "'" . $str . "'";
var_dump($str);
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.
I have a string that looks a little something like this:
$string = 'var1=foo&var2=bar&var3=blahblahblah&etc=etc';
And I would like to make another string from that, and replace it with a value, so for example it will look like this
$newstring = 'var1=foo&var2=bar&var3=$myVariable&etc=etc';
so var3 in the new string will be the value of $myVariable.
How can this be achieved?
No need for regex; built in URL functions should work more reliably.
// Parse the url first
$url = parse_url($string);
// Parse your query string into an array
parse_str($url['query'], $qs);
// Replace the var3 key with your variable
$qs['var3'] = $myVariable;
// Convert the array back into a query string
$url['query'] = http_build_query($qs);
// Convert the $url array back into a URL
$newstring = http_build_url($url);
Check out http_build_query and parse_str. This will append a var3 variable even if there isn't one, it will URL encode $myVariable, and its more readable than using preg_replace.
You can use the method preg_replace for that. Here comes an example
<?php
$string = 'var1=foo&var2=bar&var3=blahblahblah&etc=etc';
$var = 'foo';
echo preg_replace('/var3=(.*)&/', 'var3=' . $var . '&', $string);