• influxdb-client-php
    • Note: Use this client library with InfluxDB 2.x and InfluxDB 1.8+ ( see details ). For connecting to InfluxDB 1.7 or earlier instances, use the influxdb-php client library.
    • Disclaimer: This library is a work in progress and should not be considered production ready yet.
  • Installation
    • Install the library
  • Usage
    • Creating a client
      • Client Options
    • Queries
      • Query raw
      • Synchronous query
      • Query stream
    • Writing data
      • Batching
      • Time precision
      • Configure destination
      • Data format
      • Default Tags
        • Via API
  • Advanced Usage
    • Check the server status
    • InfluxDB 1.8 API compatibility
    • InfluxDB 2.0 management API
  • Local tests
  • Contributing
  • License

    PHP - 图1influxdb-client-php

    CircleCI codecov Packagist Version License GitHub issues GitHub pull requests PHP from Packagist Slack Status

    This repository contains the reference PHP client for the InfluxDB 2.0.

    PHP - 图10Note: Use this client library with InfluxDB 2.x and InfluxDB 1.8+ (see details). For connecting to InfluxDB 1.7 or earlier instances, use the influxdb-php client library.

    PHP - 图11Disclaimer: This library is a work in progress and should not be considered production ready yet.

    PHP - 图12Installation

    The InfluxDB 2 client is bundled and hosted on https://packagist.org/.

    PHP - 图13Install the library

    The client can be installed with composer.

    1. composer require influxdata/influxdb-client-php

    PHP - 图14Usage

    PHP - 图15Creating a client

    Use InfluxDB2\Client to create a client connected to a running InfluxDB 2 instance.

    1. $client = new InfluxDB2\Client([
    2. "url" => "http://localhost:8086",
    3. "token" => "my-token",
    4. "bucket" => "my-bucket",
    5. "org" => "my-org",
    6. "precision" => InfluxDB2\Model\WritePrecision::NS
    7. ]);

    PHP - 图16Client Options

    OptionDescriptionTypeDefault
    bucketDefault destination bucket for writesStringnone
    orgDefault organization bucket for writesStringnone
    precisionDefault precision for the unix timestamps within the body line-protocolStringnone

    PHP - 图17Queries

    The result retrieved by QueryApi could be formatted as a:

    1. Raw query response
    2. Flux data structure: FluxTable, FluxColumn and FluxRecord
    3. Stream of FluxRecord

    PHP - 图18Query raw

    Synchronously executes the Flux query and return result as unprocessed String

    1. $this->client = new Client([
    2. "url" => "http://localhost:8086",
    3. "token" => "my-token",
    4. "bucket" => "my-bucket",
    5. "precision" => WritePrecision::NS,
    6. "org" => "my-org",
    7. "debug" => false
    8. ]);
    9. $this->queryApi = $this->client->createQueryApi();
    10. $result = $this->queryApi->queryRaw(
    11. 'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');

    PHP - 图19Synchronous query

    Synchronously executes the Flux query and return result as a Array of FluxTables

    1. $this->client = new Client([
    2. "url" => "http://localhost:8086",
    3. "token" => "my-token",
    4. "bucket" => "my-bucket",
    5. "precision" => WritePrecision::NS,
    6. "org" => "my-org",
    7. "debug" => false
    8. ]);
    9. $this->queryApi = $this->client->createQueryApi();
    10. $result = $this->queryApi->query(
    11. 'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');

    This can then easily be encoded to JSON with json_encode

    1. header('Content-type:application/json;charset=utf-8');
    2. echo json_encode( $result, JSON_PRETTY_PRINT ) ;

    PHP - 图20Query stream

    Synchronously executes the Flux query and return stream of FluxRecord

    1. $this->client = new Client([
    2. "url" => "http://localhost:8086",
    3. "token" => "my-token",
    4. "bucket" => "my-bucket",
    5. "precision" => WritePrecision::NS,
    6. "org" => "my-org",
    7. "debug" => false
    8. ]);
    9. $this->queryApi = $this->client->createQueryApi();
    10. $parser = $this->queryApi->queryStream(
    11. 'from(bucket:"my-bucket") |> range(start: 1970-01-01T00:00:00.000000001Z) |> last()');
    12. foreach ($parser->each() as $record)
    13. {
    14. ...
    15. }

    PHP - 图21Writing data

    The WriteApi supports synchronous and batching writes into InfluxDB 2.0. In default api uses synchronous write. To enable batching you can use WriteOption.

    1. $client = new InfluxDB2\Client(["url" => "http://localhost:8086", "token" => "my-token",
    2. "bucket" => "my-bucket",
    3. "org" => "my-org",
    4. "precision" => InfluxDB2\Model\WritePrecision::NS
    5. ]);
    6. $write_api = $client->createWriteApi();
    7. $write_api->write('h2o,location=west value=33i 15');

    PHP - 图22Batching

    The writes are processed in batches which are configurable by WriteOptions:

    PropertyDescriptionDefault Value
    writeTypetype of write SYNCHRONOUS / BATCHING /SYNCHRONOUS
    batchSizethe number of data point to collect in batch10
    retryIntervalthe number of milliseconds to retry unsuccessful write. The retry interval is “exponentially” used when the InfluxDB server does not specify “Retry-After” header.5000
    jitterIntervalthe number of milliseconds before the data is written increased by a random amount0
    maxRetriesthe number of max retries when write fails5
    maxRetryDelaymaximum delay when retrying write in milliseconds180000
    exponentialBasethe base for the exponential retry delay, the next delay is computed as retryInterval * exponentialBase^(attempts-1)5
    1. use InfluxDB2\Client;
    2. use InfluxDB2\WriteType as WriteType;
    3. $client = new Client(["url" => "http://localhost:8086", "token" => "my-token",
    4. "bucket" => "my-bucket",
    5. "org" => "my-org",
    6. "precision" => InfluxDB2\Model\WritePrecision::NS
    7. ]);
    8. $writeApi = $client->createWriteApi(
    9. ["writeType" => WriteType::BATCHING, 'batchSize' => 1000]);
    10. foreach (range(1, 10000) as $number) {
    11. $writeApi->write("mem,host=aws_europe,type=batch value=1i $number");
    12. }
    13. // flush remaining data
    14. $writeApi->close();

    PHP - 图23Time precision

    Configure default time precision:

    1. $client = new InfluxDB2\Client(["url" => "http://localhost:8086", "token" => "my-token",
    2. "bucket" => "my-bucket",
    3. "org" => "my-org",
    4. "precision" => \InfluxDB2\Model\WritePrecision::NS
    5. ]);

    Configure precision per write:

    1. $client = new InfluxDB2\Client([
    2. "url" => "http://localhost:8086",
    3. "token" => "my-token",
    4. "bucket" => "my-bucket",
    5. "org" => "my-org",
    6. ]);
    7. $writeApi = $client->createWriteApi();
    8. $writeApi->write('h2o,location=west value=33i 15', \InfluxDB2\Model\WritePrecision::MS);

    Allowed values for precision are:

    • WritePrecision::NS for nanosecond
    • WritePrecision::US for microsecond
    • WritePrecision::MS for millisecond
    • WritePrecision::S for second

    PHP - 图24Configure destination

    Default bucket and organization destination are configured via InfluxDB2\Client:

    1. $client = new InfluxDB2\Client([
    2. "url" => "http://localhost:8086",
    3. "token" => "my-token",
    4. "bucket" => "my-bucket",
    5. ]);

    but there is also possibility to override configuration per write:

    1. $client = new InfluxDB2\Client(["url" => "http://localhost:8086", "token" => "my-token"]);
    2. $writeApi = $client->createWriteApi();
    3. $writeApi->write('h2o,location=west value=33i 15', \InfluxDB2\Model\WritePrecision::MS, "production-bucket", "customer-1");

    PHP - 图25Data format

    The data could be written as:

    1. string that is formatted as a InfluxDB’s line protocol
    2. array with keys: name, tags, fields and time
    3. Data Point structure
    4. Array of above items
    1. $client = new InfluxDB2\Client([
    2. "url" => "http://localhost:8086",
    3. "token" => "my-token",
    4. "bucket" => "my-bucket",
    5. "org" => "my-org",
    6. "precision" => InfluxDB2\Model\WritePrecision::US
    7. ]);
    8. $writeApi = $client->createWriteApi();
    9. //data in Point structure
    10. $point=InfluxDB2\Point::measurement("h2o")
    11. ->addTag("location", "europe")
    12. ->addField("level",2)
    13. ->time(microtime(true));
    14. $writeApi->write($point);
    15. //data in array structure
    16. $dataArray = ['name' => 'cpu',
    17. 'tags' => ['host' => 'server_nl', 'region' => 'us'],
    18. 'fields' => ['internal' => 5, 'external' => 6],
    19. 'time' => microtime(true)];
    20. $writeApi->write($dataArray);
    21. //write lineprotocol
    22. $writeApi->write('h2o,location=west value=33i 15');

    PHP - 图26Default Tags

    Sometimes is useful to store same information in every measurement e.g. hostname, location, customer. The client is able to use static value, app settings or env variable as a tag value.

    The expressions:

    • California Miner - static value
    • ${env.hostname} - environment property
    PHP - 图27Via API
    1. $this->client = new Client([
    2. "url" => "http://localhost:8086",
    3. "token" => "my-token",
    4. "bucket" => "my-bucket",
    5. "precision" => WritePrecision::NS,
    6. "org" => "my-org",
    7. "tags" => ['id' => '132-987-655',
    8. 'hostname' => '${env.Hostname}']
    9. ]);
    10. $writeApi = $this->client->createWriteApi(null, ['data_center' => '${env.data_center}']);
    11. $writeApi->pointSettings->addDefaultTag('customer', 'California Miner');
    12. $point = Point::measurement('h2o')
    13. ->addTag('location', 'europe')
    14. ->addField('level', 2);
    15. $this->writeApi->write($point);

    PHP - 图28Advanced Usage

    PHP - 图29Check the server status

    Server availability can be checked using the $client->health(); method. That is equivalent of the influx ping.

    PHP - 图30InfluxDB 1.8 API compatibility

    InfluxDB 1.8.0 introduced forward compatibility APIs for InfluxDB 2.0. This allow you to easily move from InfluxDB 1.x to InfluxDB 2.0 Cloud or open source.

    The following forward compatible APIs are available:

    APIEndpointDescription
    QueryApi.php/api/v2/queryQuery data in InfluxDB 1.8.0+ using the InfluxDB 2.0 API and Flux (endpoint should be enabled by flux-enabled option)
    WriteApi.php/api/v2/writeWrite data to InfluxDB 1.8.0+ using the InfluxDB 2.0 API
    HealthApi.php/healthCheck the health of your InfluxDB instance

    For detail info see InfluxDB 1.8 example.

    PHP - 图31InfluxDB 2.0 management API

    InfluxDB 2.0 API client is generated using influxdb-clients-apigen. Sources are in InfluxDB2\Service\ and InfluxDB2\Model\ packages.

    The following example shows how to use OrganizationService and BucketService to create a new bucket.

    1. require __DIR__ . '/../vendor/autoload.php';
    2. use InfluxDB2\Client;
    3. use InfluxDB2\Model\BucketRetentionRules;
    4. use InfluxDB2\Model\Organization;
    5. use InfluxDB2\Model\PostBucketRequest;
    6. use InfluxDB2\Service\BucketsService;
    7. use InfluxDB2\Service\OrganizationsService;
    8. $organization = 'my-org';
    9. $bucket = 'my-bucket';
    10. $token = 'my-token';
    11. $client = new Client([
    12. "url" => "http://localhost:8086",
    13. "token" => $token,
    14. "bucket" => $bucket,
    15. "org" => $organization,
    16. "precision" => InfluxDB2\Model\WritePrecision::S
    17. ]);
    18. function findMyOrg($client): ?Organization
    19. {
    20. /** @var OrganizationsService $orgService */
    21. $orgService = $client->createService(OrganizationsService::class);
    22. $orgs = $orgService->getOrgs()->getOrgs();
    23. foreach ($orgs as $org) {
    24. if ($org->getName() == $client->options["org"]) {
    25. return $org;
    26. }
    27. }
    28. return null;
    29. }
    30. $bucketsService = $client->createService(BucketsService::class);
    31. $rule = new BucketRetentionRules();
    32. $rule->setEverySeconds(3600);
    33. $bucketName = "example-bucket-" . microtime();
    34. $bucketRequest = new PostBucketRequest();
    35. $bucketRequest->setName($bucketName)
    36. ->setRetentionRules([$rule])
    37. ->setOrgId(findMyOrg($client)->getId());
    38. //create bucket
    39. $respBucket = $bucketsService->postBuckets($bucketRequest);
    40. print $respBucket;
    41. $client->close();

    PHP - 图32Local tests

    1. # run unit & integration tests
    2. make test

    PHP - 图33Contributing

    Bug reports and pull requests are welcome on GitHub at https://github.com/influxdata/influxdb-client-php.

    PHP - 图34License

    The gem is available as open source under the terms of the MIT License.