Home > Backend Development > PHP Problem > How to convert string to json data in php

How to convert string to json data in php

青灯夜游
Release: 2023-03-08 15:42:01
Original
6026 people have browsed it

php method to convert string to json data: first use the explode() function to convert the string into array format; then use the json_encode() function to convert the array into json data, the syntax format is "json_encode (array,true)".

How to convert string to json data in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php converts strings to json Data

<?php
$str = &#39;hello world&#39;;
//将字符串转换为数组
$arr = explode(&#39; &#39;,$str,0);
print_r($arr);
print "<br>";

//将数组转换为json
$json=json_encode($arr,true);
print_r($json);

?>
Copy after login

Output:

How to convert string to json data in php

[Recommended learning: "PHP Video Tutorial"]

Related function description:

1. explode() function

explode() function uses one string to split another string and returns an array composed of strings . Syntax:

explode(separator,string,limit)
Copy after login

How to convert string to json data in php

Return value: Returns a string array.​

2. json_encode() function

json_encode() is used to JSON encode variables. If the function is successfully executed, it returns JSON data, otherwise it returns FALSE. Syntax:

json_encode ( $value [, $options = 0 ] )
Copy after login

Parameters

  • value: The value to be encoded. This function is only valid for UTF-8 encoded data

  • options: Binary mask composed of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of How to convert string to json data in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template