Getting Started
Parse HCL (HashiCorp Configuration Language) content in PHP.
Use case: Reading Terraform, Nomad, Consul, or any HCL-based configuration files in your PHP application.
Installation
Section titled “Installation”composer require cline/hclBasic Parsing
Section titled “Basic Parsing”Parse HCL String
Section titled “Parse HCL String”use Cline\Hcl\Hcl;
$hcl = <<<'HCL'name = "my-app"version = "1.0.0"enabled = trueport = 8080HCL;
$data = Hcl::parse($hcl);
// Result:// [// 'name' => 'my-app',// 'version' => '1.0.0',// 'enabled' => true,// 'port' => 8080,// ]Parse HCL File
Section titled “Parse HCL File”use Cline\Hcl\Hcl;
$data = Hcl::parseFile('/path/to/config.hcl');Supported Value Types
Section titled “Supported Value Types”$hcl = <<<'HCL'# Stringsname = "hello"path = "/usr/local/bin"
# Numberscount = 42rate = 3.14scientific = 1e10
# Booleansenabled = truedisabled = false
# Nulloptional = null
# Arraysports = [80, 443, 8080]tags = ["web", "api", "production"]
# Objects/Mapsconfig = { timeout = 30 retries = 3}HCL;
$data = Hcl::parse($hcl);Blocks
Section titled “Blocks”HCL blocks are converted to nested arrays:
$hcl = <<<'HCL'resource "aws_instance" "web" { ami = "ami-12345" instance_type = "t2.micro"
tags = { Name = "WebServer" }}HCL;
$data = Hcl::parse($hcl);
// Access nested data:$ami = $data['resource']['aws_instance']['web']['ami'];// 'ami-12345'Multiple Blocks
Section titled “Multiple Blocks”Multiple blocks of the same type are merged:
$hcl = <<<'HCL'variable "region" { default = "us-west-2"}
variable "instance_type" { default = "t2.micro"}HCL;
$data = Hcl::parse($hcl);
// [// 'variable' => [// 'region' => ['default' => 'us-west-2'],// 'instance_type' => ['default' => 't2.micro'],// ],// ]String Interpolation
Section titled “String Interpolation”Template expressions are evaluated when possible:
$hcl = <<<'HCL'name = "app"greeting = "Hello, ${name}!"HCL;
$data = Hcl::parse($hcl);// greeting => 'Hello, app!'Comments
Section titled “Comments”Both line and block comments are supported:
# This is a line comment// This is also a line comment
/* This is a block comment */
name = "value"Error Handling
Section titled “Error Handling”use Cline\Hcl\Hcl;use Cline\Hcl\Exceptions\ParserException;
try { $data = Hcl::parse('invalid { content');} catch (ParserException $e) { echo "Parse error: " . $e->getMessage(); // Includes line and column information}