Home  >  Article  >  Backend Development  >  How to convert MySQL result arrays to JSON in PHP (pre-5.2.0)?

How to convert MySQL result arrays to JSON in PHP (pre-5.2.0)?

DDD
DDDOriginal
2024-10-31 04:31:01336browse

How to convert MySQL result arrays to JSON in PHP (pre-5.2.0)?

Converting MySQL Result Array to JSON

Problem:

You want to convert the result array from a MySQL query to JSON format in PHP, preferably with a solution that is compatible with PHP versions below 5.2.0.

Solution:

For PHP versions 5.2.0 and above:

Utilize the json_encode() function:

<code class="php">echo json_encode($row);</code>

For PHP versions below 5.2.0:

Utilize the JSON class from the PEAR package:

  1. Install the PEAR package:
pear install JSON
  1. Include the JSON class:
<code class="php">include_once 'JSON.php';</code>
  1. Create a new JSON object:
<code class="php">$json = new Services_JSON;</code>
  1. Convert the result array to JSON:
<code class="php">echo $json->encode($row);</code>

The above is the detailed content of How to convert MySQL result arrays to JSON in PHP (pre-5.2.0)?. 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