CakeFest 2024: The Official CakePHP Conference

yaml_emit

(PECL yaml >= 0.5.0)

yaml_emitYAML 形式にした値を返す

説明

yaml_emit(
    mixed $data,
    int $encoding = YAML_ANY_ENCODING,
    int $linebreak = YAML_ANY_BREAK,
    array $callbacks = null
): string

data で渡したデータを YAML 形式にして返します。

パラメータ

data

エンコードしたいデータ。リソース型以外の任意の型が使えます。

encoding

出力時の文字エンコーディング。 YAML_ANY_ENCODINGYAML_UTF8_ENCODINGYAML_UTF16LE_ENCODINGYAML_UTF16BE_ENCODING のいずれか。

linebreak

出力時の改行形式。 YAML_ANY_BREAKYAML_CR_BREAKYAML_LN_BREAKYAML_CRLN_BREAK のいずれか。

callbacks

YAML ノードの発行用のコンテンツハンドラ。 クラス名 => callable 形式の連想配列となります。 詳細は発行コールバック を参照ください。

戻り値

成功した場合に YAML 形式の文字列を返します。

変更履歴

バージョン 説明
PECL yaml 1.1.0 callbacks パラメータが追加されました。

例1 yaml_emit() の例

<?php
$addr
= array(
"given" => "Chris",
"family"=> "Dumars",
"address"=> array(
"lines"=> "458 Walkman Dr.
Suite #292"
,
"city"=> "Royal Oak",
"state"=> "MI",
"postal"=> 48046,
),
);
$invoice = array (
"invoice"=> 34843,
"date"=> 980208000,
"bill-to"=> $addr,
"ship-to"=> $addr,
"product"=> array(
array(
"sku"=> "BL394D",
"quantity"=> 4,
"description"=> "Basketball",
"price"=> 450,
),
array(
"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.",
);
var_dump(yaml_emit($invoice));
?>

上の例の出力は、 たとえば以下のようになります。

string(628) "---
invoice: 34843
date: 980208000
bill-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              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.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
"

参考

add a note

User Contributed Notes 2 notes

up
1
josh dot sickmate at gmail dot com
4 years ago
There isn't an option for indenting depth so it's always two spaces. If you want more than this you can use a simple regex.

Converting from two spaces to four:
<?php
$yaml
= preg_replace('/^( +)/m', '$1$1', $yaml);
?>

Add two more $1 into the replacement for eight spaces.
up
1
nsa at succhia dot cz
10 months ago
Note that NULL values will be converted to the tilde character "~".

This can be somehow counter-intuitive, but that is absolutely legit, and it seems it is a standard recognized by every Yaml parser. So, don't worry about that. Yaml reference:

http://yaml.org/spec/1.2-old/spec.html#id2805071
To Top