In PHP, you can use the json_encode() function to convert the array into json data, the syntax is "json_encode($arr)"; you can use the str_replace() or preg_replace() function to convert double quotes into single Quotes, just find the double quotes in the string and replace them with single quotes, the syntax is "str_replace('"',"'",string)" or "preg_replace('/\"/',"' ", string)".
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
php will convert the array For json data
In php, you can use the json_encode() function to convert the array into json data.
<?php header('content-type:text/html;charset=utf-8'); $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo "原数组:"; var_dump($arr); echo "转为json后:<br><br>"; echo json_encode($arr); ?>
Description: json_encode() function
json_encode() function can JSON encode variables
Syntax:
json_encode ( $value [, $options = 0 ] )
Returns a string, containing the representation of value in JSON form.
Note:
1. $value is the value to be encoded, and this function is only valid for UTF8 encoded data;
2. options: consists of the following constants Binary masks: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT;
3. The second parameter is generally not needed;
4. JSON data is actually a string , you can use var_dump() to print it out to see the data type;
5. If the execution is successful, JSON data will be returned, otherwise FALSE will be returned.
Return value:
Returns a JSON encoded string on success or false on failure.
PHP Convert double quotes to single quotes
Method 1: Use str_replace() function
str_replace() function replaces some characters in a string (case sensitive).
Just use this function to find double quotes in a string and replace them with single quotes.
Note: The same type of quotation marks cannot be nested (single quotation marks cannot contain single quotation marks, and double quotation marks cannot contain double quotation marks). You can use "outer double and inner single" or "outer single and inner double" "Format
Example:
<?php header('content-type:text/html;charset=utf-8'); $param = '{"id":"12", "name":"hi"}'; echo "原字符串:".$param."<br>"; $new = str_replace('"',"'",$param); echo "新字符串:".$new; ?>
Method 2: Use the preg_replace() function with regular expressions to convert single quotes The preg_replace function performs a regular expression search and replace for double quotes
.
Example:
<?php header('content-type:text/html;charset=utf-8'); $param = '{"id":"12", "name":"hi","ang":"23"}'; echo "原字符串:".$param."<br>"; $new = preg_replace('/\"/', "'", $param); echo "新字符串:".$new; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert array to json data in php, convert double quotes to single quotes. For more information, please follow other related articles on the PHP Chinese website!