[PHP8] Install and use PECL YAML function (YAML parser) with Docker

Aug 28, 2020 PHP YAML PECL Docker PHP8

PHP's [YAML Functions](https://www.php.net/manual/en/ref.yaml.php) is not bundled with PHP by default.

To parse (parse and convert) YAML data into a PHP array or to parse YAML data from a PHP array into YAML data with a YAML function You need to install the PECL extension module.

However, PECL is not installed on the latest (as of 08/28/2020) php:8.0.0beta2 and php:8.0.0beta2-alpine images. It seems that PEAR/PECL installer has been removed from PHP 7.4 or later.

TL; DR

I need to build PECL from source, but that’s too cumbersome, so I created an image with the pecl command.

docker pull keinos/php8-jit:latest
$ docker run --rm keinos/php8-jit pecl version
PEAR Version: 1.10.12
PHP Version: 8.0.0-dev
Zend Engine Version: 4.0.0-dev
Running on: Linux 3fc54c34122a 4.19.76-linuxkit #1 SMP Tue May 26 11:42:35 UTC 2020 x86_64

We also allow the PECL package to be installed from source.

docker-php-ext-pecl install yaml

TS; DR

FROM keinos/php8-jit:latest

USER root

COPY sample.php /app/sample.php

RUN \
    apk --no-cache add yaml-dev && \
    docker-php-ext-pecl install yaml

ENTRYPOINT ["php", "/app/sample.php"]
<?php

// YAML sample string
$yaml = <<<EOD
- --
invoice: 34843
date: "2001-01-23"
bill-to: &id001
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to: *id001
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
EOD;

// Parse YAML string into PHP array
$parsed = yaml_parse($yaml);

// comparison test
$actual = json_encode($parsed);
$expect ='{"invoice":34843,"date":"2001-01-23","bill-to":{"given":"Chris","family":"Dumars","address": {"lines":"458 Walkman Dr.\n Suite #292","city":"Royal Oak","state":"MI","postal":48046}},"ship-to":{" given":"Chris","family":"Dumars","address":{"lines":"458 Walkman Dr.\n Suite #292","city":"Royal Oak","state":" MI","postal":48046}},"product":[{"sku":"BL394D","quantity":4,"description":"Basketball","price":450},{"sku" :"BL4438H","quantity":1,"description":"Super Hoop","price":2392}],"tax":251.42,"total":4443.52,"comments":"Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338."}';

echo'- Function test ...', ($expect === $actual) ?'OK' :'NG', PHP_EOL;

References