- PHP Client: other versions:
- Overview
- Quickstart
- Installation
- Configuration
- Inline Host Configuration
- Extended Host Configuration
- Authorization and Encryption
- Set retries
- Enabling the Logger
- Configure the HTTP Handler
- Setting the Connection Pool
- Setting the Connection Selector
- Setting the Serializer
- Setting a custom ConnectionFactory
- Set the Endpoint closure
- Building the client from a configuration hash
- Per-request configuration
- Future Mode
- Dealing with JSON Arrays and Objects in PHP
- Index Management Operations
- Indexing Documents
- Getting Documents
- Updating Documents
- Deleting documents
- Search Operations
- Namespaces
- Security
- Connection Pool
- Selectors
- Serializers
- PHP Version Requirement
- Breaking changes from 5.x
- Community DSLs
- Community Integrations
- Reference - Endpoints
- Elasticsearch\Client
- Elasticsearch\ClientBuilder
- Elasticsearch\Namespaces\CatNamespace
- Elasticsearch\Namespaces\ClusterNamespace
- Elasticsearch\Namespaces\IndicesNamespace
- Elasticsearch\Namespaces\IngestNamespace
- Elasticsearch\Namespaces\NodesNamespace
- Elasticsearch\Namespaces\RemoteNamespace
- Elasticsearch\Namespaces\SnapshotNamespace
- Elasticsearch\Namespaces\TasksNamespace
Empty Objects
editEmpty Objects
editThe Elasticsearch API uses empty JSON objects in several locations, and this can cause problems for PHP. Unlike other languages, PHP does not have a "short" notation for empty objects and so many developers are unaware how to specify an empty object.
Consider adding a Highlight to a query:
{ "query" : { "match" : { "content" : "quick brown fox" } }, "highlight" : { "fields" : { "content" : {} } } }
The problem is that PHP will automatically convert "content" : {}
into "content" : []
, which is no longer valid
Elasticsearch DSL. We need to tell PHP that the empty object is explicitly an object, not an array. To define this
query in PHP, you would do:
$params['body'] = array( 'query' => array( 'match' => array( 'content' => 'quick brown fox' ) ), 'highlight' => array( 'fields' => array( 'content' => new \stdClass() ) ) ); $results = $client->search($params);
We use the generic PHP stdClass object to represent an empty object. The JSON will now encode correctly. |
By using an explicit stdClass object, we can force the json_encode
parser to correctly output an empty object, instead
of an empty array. Sadly, this verbose solution is the only way to acomplish the goal in PHP…there is no "short"
version of an empty object.