php array to json string

json_encode

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)

json_encode — Возвращает JSON-представление данных

Описание

На кодирование влияет параметр flags и, кроме того, кодирование значений типа float зависит от значения serialize_precision.

Список параметров

Функция работает только с кодировкой UTF-8.

PHP реализует надмножество JSON, который описан в первоначальном » RFC 7159.

Устанавливает максимальную глубину. Должен быть больше нуля.

Возвращаемые значения

Возвращает строку ( string ), закодированную JSON или false в случае возникновения ошибки.

Список изменений

Примеры

Пример #1 Пример использования json_encode()

Результат выполнения данного примера:

Пример #2 Пример использования json_encode() с опциями

Результат выполнения данного примера:

Пример #3 Пример использования опции JSON_NUMERIC_CHECK

Результатом выполнения данного примера будет что-то подобное:

Пример #4 Пример с последовательными индексами, начинающимися с нуля, и непоследовательными индексами массивов

Результат выполнения данного примера:

Пример #5 Пример использования опции JSON_PRESERVE_ZERO_FRACTION

Результат выполнения данного примера:

Примечания

в случае возникновения ошибки кодирования можно использовать json_last_error() для определения точной ошибки.

При кодировании массива в случае, если его индексы не являются последовательными числами от нуля, то все индексы кодируются в строковые ключи для каждой пары индекс-значение.

Смотрите также

User Contributed Notes 39 notes

This isn’t mentioned in the documentation for either PHP or jQuery, but if you’re passing JSON data to a javascript program, make sure your program begins with:

Are you sure you want to use JSON_NUMERIC_CHECK, really really sure?

Just watch this usecase:

// International phone number
json_encode (array( ‘phone_number’ => ‘+33123456789’ ), JSON_NUMERIC_CHECK );
?>

And then you get this JSON:

Maybe it makes sense for PHP (as is_numeric(‘+33123456789’) returns true), but really, casting it as an int?!

So be careful when using JSON_NUMERIC_CHECK, it may mess up with your data!

A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential.

SOLUTION: Use array_values() to re-index the array.

This is intended to be a simple readable json encode function for PHP 5.3+ (and licensed under GNU/AGPLv3 or GPLv3 like you prefer):

I came across the «bug» where running json_encode() over a SimpleXML object was ignoring the CDATA. I ran across http://bugs.php.net/42001 and http://bugs.php.net/41976, and while I agree with the poster that the documentation should clarify gotchas like this, I was able to figure out how to workaround it.

You need to convert the SimpleXML object back into an XML string, then re-import it back into SimpleXML using the LIBXML_NOCDATA option. Once you do this, then you can use json_encode() and still get back the CDATA.

Although this is not documented on the version log here, non-UTF8 handling behaviour has changed in 5.5, in a way that can make debugging difficult.

Passing a non UTF-8 string to json_encode() will make the function return false in PHP 5.5, while it will only nullify this string (and only this one) in previous versions.

PHP 5.5 has it right of course (if encoding fails, return false) but its likely to introduce errors when updating to 5.5 because previously you could get the rest of the JSON even when one string was not in UTF8 (if this string wasn’t used, you’d never notify it’s nulled)

If you are planning on using this function to serve a json file, it’s important to note that the json generated by this function is not ready to be consumed by javascript until you wrap it in parens and add «;» to the end.

It took me a while to figure this out so I thought I’d save others the aggravation.

( ‘Content-Type: text/javascript; charset=utf8’ );
header ( ‘Access-Control-Allow-Origin: http://www.example.com/’ );
header ( ‘Access-Control-Max-Age: 3628800’ );
header ( ‘Access-Control-Allow-Methods: GET, POST, PUT, DELETE’ );

This function is more accurate and faster than, for example, that one:
http://www.php.net/manual/ru/function.json-encode.php#89908
(RU: эта функция работает более точно и быстрее, чем указанная выше).

Please note that there was an (as of yet) undocumented change to the json_encode() function between 2 versions of PHP with respect to JSON_PRETTY_PRINT:

In version 5.4.21 and earlier, an empty array [] using JSON_PRETTY_PRINT would be rendered as 3 lines, with the 2nd one an empty (indented) line, i.e.:
«data»: [

In version 5.4.34 and above, an empty array [] using JSON_PRETTY_PRINT would be rendered as exactly [] at the spot where it occurs, i.e.
«data: [],

This is not mentioned anywhere in the PHP changelist and migration documentations; neither on the json_encode documentation page.

This is very useful to know when you are parsing the JSON using regular expressions to manually insert portions of data, as is the case with my current use-case (working with JSON exports of over several gigabytes requires sub-operations and insertion of data).

Solution for UTF-8 Special Chars.

If you need to force an object (ex: empty array) you can also do:

Be careful with floating values in some locales (e.g. russian) with comma («,») as decimal point. Code:

Which is NOT a valid JSON markup. You should convert floating point variable to strings or set locale to something like «LC_NUMERIC, ‘en_US.utf8′» before using json_encode.

Here is a bit more on creating an iterator to get at those pesky private/protected variables:

class Kit implements IteratorAggregate <

If I want to encode object whith all it’s private and protected properties, then I implements that methods in my object:

Found that much more simple than regular expressions with PHP serialized objects.

For anyone who would like to encode arrays into JSON, but is using PHP 4, and doesn’t want to wrangle PECL around, here is a function I wrote in PHP4 to convert nested arrays into JSON.

I don’t make a claim that this function is by any means complete (for example, it doesn’t handle objects) so if you have any improvements, go for it.

// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.

Источник

How to convert a string to JSON object in PHP

I have the following result from an SQL query:

It is currently a string in PHP. I know it’s already in JSON form, is there an easy way to convert this to a JSON object?

I need it to be an object so I can add an extra item/element/object like what «Coords» already is.

4 Answers 4

What @deceze said is correct, it seems that your JSON is malformed, try this:

Use json_decode to convert String into Object ( stdClass ) or array: http://php.net/manual/en/function.json-decode.php

[edited]

I did not understand what do you mean by «an official JSON object», but suppose you want to add content to json via PHP and then converts it right back to JSON?

assuming you have the following variable:

You should convert it to Object (stdClass):

But working with stdClass is more complicated than PHP-Array, then try this (use second param with true ):

$manage = json_decode($data, true);

adding an item:

remove first item:

any chance you want to save to json to a database or a file:

I hope I have understood your question.

php array to json string. Смотреть фото php array to json string. Смотреть картинку php array to json string. Картинка про php array to json string. Фото php array to json string

To convert a valid JSON string back, you can use the json_decode() method.

To convert it back to an object use this method:

And to convert it to a associative array, set the second parameter to true :

By the way to convert your mentioned string back to either of those, you should have a valid JSON string. To achieve it, you should do the following:

Источник

Array to String PHP?

I want to store it as a single string in my database with each entry separated by | :

php array to json string. Смотреть фото php array to json string. Смотреть картинку php array to json string. Картинка про php array to json string. Фото php array to json string

13 Answers 13

Later just use json_decode() to decode the string from your DB. Anything else is useless, JSON keeps the array relationship intact for later usage!

WHY JSON : You can use it with most of the programming languages, string created by serialize() function of php is readable in PHP only, and you will not like to store such things in your databases specially if database is shared among applications written in different programming languages

One of the Best way:

php array to json string. Смотреть фото php array to json string. Смотреть картинку php array to json string. Картинка про php array to json string. Фото php array to json string

No, you don’t want to store it as a single string in your database like that.

You could use serialize() but this will make your data harder to search, harder to work with, and wastes space.

You could do some other encoding as well, but it’s generally prone to the same problem.

The whole reason you have a DB is so you can accomplish work like this trivially. You don’t need a table to store arrays, you need a table that you can represent as an array.

You would simply select the data from the table with SQL, rather than have a table that looks like:

That’s not how anybody designs a schema in a relational database, it totally defeats the purpose of it.

Источник

PHP json_encode: How to Convert PHP Array to JSON

JSON stands for JavaScript Object Notation. It is data saved in the .json file and consists of a series of key/value pairs. JSON is used to transfer the data between the server and the browser. Here is a primary example of what might be in a .json string.

Arrays in PHP will also be converted into JSON when using the PHP function json_encode(). You can find the example of covert PHP Array to JSON.

If you’re passing JSON data to a javascript program, make sure your program begins with:

PHP json_encode()

PHP json_encode() is a built-in function that converts a PHP value to JSON value. Objects in PHP can be converted into JSON by using a function called json_encode(). The json_encode() function returns the string, if the function works.

Syntax

The syntax of json_encode() function is following.

Arguments

The value parameter is required and of type mixed.

The options Bitmask comprising of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.

Return Value

The json_encode() function returns a string, if the function works.

Example

Let’s see the following example.

php array to json string. Смотреть фото php array to json string. Смотреть картинку php array to json string. Картинка про php array to json string. Фото php array to json string

PHP Object to JSON

To convert PHP Object to JSON, use the json_encode() function. The json_encode() method can convert PHP Object to JSON. So objects can easily convert into JSON using the json_encode() method.

So, we have defined one class App and then created an object and set the properties and convert the object to JSON, and print that JSON output. The output is the following.

php array to json string. Смотреть фото php array to json string. Смотреть картинку php array to json string. Картинка про php array to json string. Фото php array to json string

PHP String to JSON

To convert String to JSON in PHP, use the json_encode() function. PHP json_encode() function is useful to convert String to JSON object.

The output will be the same as the string.

You can use the json_encode() in any PHP Framework.

If the array keys in your PHP array are not consecutive numbers, json_encode() must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.

Use array_values() on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering.

PHP is a server-side programming language and should be used for operations that can only be performed by a server, like accessing a database.

PHP array to JSON

To convert an array to json in PHP, use the json_encode() function. The json_encode() function is used to encode a value to JSON format.

The json_encode() function converts PHP-supported data type into JSON formatted string to be returned due to JSON encode operation.

See the following code.

Convert Multidimensional PHP Array into JSON

To convert multi-dimensional array into json in PHP, use the json_encode() function. Let’s see an example where we can encode the multidimensional array.

The output of the above code is following.

php array to json string. Смотреть фото php array to json string. Смотреть картинку php array to json string. Картинка про php array to json string. Фото php array to json string

Generally, you have to use json_encode() function when you need to send an AJAX request to the server because JSON data is useful to transfer between client and server.

So converting PHP to JSON, Javascript to JSON is easy. That is why the JSON object contributes to a significant role in today’s web development.

The reverse process of json_encode is json_decode().

Decoding JSON data is as simple as encoding it. You can use a PHP json_decode() function to convert a JSON encoded string into the appropriate PHP data type.

Источник

JSON PHP Array to Javascript

in javascript, it give me errors. I was wondering if there is a limitation on what sort of php arrays JSON can/cannot do.

5 Answers 5

First you need a PHP file on a Apache server somewhere with PHP installed. Make a file like this:

localhost:8888/myfile.php

Then your JavaScript (in this example I use jQuery):

This should be a start to get PHP arrays in to your JavaScript.

As @Allendar said you can’t embed PHP inside a JS file. You could, however, add a function in your JS file to load the JSON data, and then embed that data in a script tag in your PHP file.

Edit: this is assuming you only need to get the data into JS once at page load, in which case you can skip making AJAX requests.

php array to json string. Смотреть фото php array to json string. Смотреть картинку php array to json string. Картинка про php array to json string. Фото php array to json string

Passing PHP JSON to Javascript and reading

var stuff = ; var arr = new Array(); arr= JSON.parse(stuff); document.write( arr[0].cust_code );

JSON can handle any type of array (albeit it will cast associative arrays as objects). The problem you are probably facing is that you are trying to output with PHP when the data is available only on Javascript.

To clarify: once the page has loaded, PHP cannot do anything. Only javascript can process things on client side, PHP works only on the server and has no knowledge of the state of the client.

I’ve never tried to do something like this but I think that you’re having issue because json_encode returns a json encoded string. You then need to decode this string on the javascript side of things. Try something like the following:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *