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

How to convert string to json data in php

青灯夜游
青灯夜游Original
2021-03-10 17:42:185929browse

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

?>

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)

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

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!

Statement:
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