Home >Backend Development >PHP Problem >How to convert each line of text or array into JSON format using PHP
PHP is a commonly used programming language, often used for front-end and back-end interactive development. During the development process, we may encounter the need to convert text or arrays into JSON format. This article will introduce how to use PHP to convert each line of text or array into JSON format.
Sometimes we need to convert each line in the text file into JSON format. At this time, we can use PHP The file() function reads a file as an array. The code is as follows:
$file = 'path/to/your/file.txt'; $json = array(); foreach(file($file) as $line) { $json[] = json_encode($line); }
Here we use a foreach loop to traverse each line of text, and then use the json_encode() function to convert the text into JSON form and store it in a new array $json.
Of course, you can also use other IO functions such as fopen, fgets, etc. to achieve the same effect.
In addition to converting text into JSON format, sometimes we also need to convert arrays into JSON format. PHP provides the json_encode() function, which can convert arrays into JSON format. The code is as follows:
$arr = array('foo' => 'bar', 'bar' => 'foo',); $json = json_encode($arr);
Here we define an associative array $arr, and then use the json_encode() function to convert the array into JSON format.
At the same time, the json_encode() function also supports multi-dimensional arrays. For example, we can convert a multidimensional array into JSON format. The code is as follows:
$arr = array( 'foo' => 'bar', 'bar' => 'foo', 'multi' => array( 'dimensional' => array( 'array' => 'value' ) ) ); $json = json_encode($arr);
When our string contains Chinese characters, it is possible if we directly convert it into JSON format Garbled characters will appear. PHP provides the second parameter $option of the json_encode() function, which can set JSON escape options. You can use the JSON_UNESCAPED_UNICODE option to ensure that Chinese characters are displayed normally, as shown below:
$arr = array('name' => '中文', 'age' => 20); $json = json_encode($arr, JSON_UNESCAPED_UNICODE);
In the above code, we pass the second parameter JSON_UNESCAPED_UNICODE to ensure that Chinese characters are displayed normally.
Summary
With the above method, we can easily convert each line of text or array into JSON format and use Chinese characters in JSON. When using the json_encode() function, pay attention to setting the option parameters appropriately to ensure that the converted JSON format meets the requirements and avoid problems such as garbled characters.
The above is the detailed content of How to convert each line of text or array into JSON format using PHP. For more information, please follow other related articles on the PHP Chinese website!