$data = array( 'name' => 'John', 'age' => 30, 'city' => 'New York' ); $json = json_encode($data); echo $json;
$books = array( array( 'title' => 'The Great Gatsby', 'author' => 'F. Scott Fitzgerald', 'year' => 1925 ), array( 'title' => 'To Kill a Mockingbird', 'author' => 'Harper Lee', 'year' => 1960 ) ); $json = json_encode($books); echo $json;This code creates an array of books, encodes it as a JSON string using json_encode(), and then prints the string to the screen. The output will be: [{"title":"The Great Gatsby","author":"F. Scott Fitzgerald","year":1925},{"title":"To Kill a Mockingbird","author":"Harper Lee","year":1960}] The jsonEncode function is part of the PHP Standard Library, which means it is included by default in all installations of PHP.