PHP code example of civicrm / php-array-doc

1. Go to this page and download the library: Download civicrm/php-array-doc library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

civicrm / php-array-doc example snippets



return [
  // First item is a string.
  'key_1' => 'value_1',

  // Second item is an array of floats.
  'key_2' => [2.1, 2.2, 2.3],

  // Third item is an array.
  'key_3' => [
    'part_a' => 'Apple',
    'part_b' => 'Banana',
  ]
];


use MyHelper as H;

return [
  'id' => 1234,
  'name' => 'greeter',
  'label' => H::translate('Hello World'),
];

use MyHelper as H;

return H::record([
  'id' => 1234,
  'name' => 'greeter',
  'label' => H::translate('Hello World'),
]);

use MyHelper as H;

return H::record([
  'id' => 1234,
  'name' => 'greeter',
  'label' => fn() => H::translate('Hello World'),
]);

$doc = PhpArrayDocument::create();
$doc->getRoot()->importData([
  'id' => 1234,
  'name' => 'greeting',
  'label' => ScalarNode::create('Hello World')->setFactory('E::ts'),
]);

$file = 'my.data.php';
file_put_contents($file, (new Printer())->print($doc));

$file = 'my.data.php';
$doc = (new Parser())->parse(file_get_contents($file));

$root = $doc->getRoot();
$root['id'] = ScalarNode::create(100);
$root['name'] = ScalarNode::create('greeting');
$root['label'] = ScalarNode::create('Hello World')->setFactory('E::ts');

file_put_contents($file, (new Printer())->print($doc));

$file = 'my.data.php';
$doc = (new Parser())->parse(file_get_contents($file));

foreach ($doc->getRoot()->walkNodes() as $node) {
  if ($node->getFactory() === 'OldHelper::method') {
    $node->setFactory('NewHelper::method');
  }
}

file_put_contents($file, (new Printer())->print($doc));
xml
> <document xmlns:h="MyHelper">
>   <array>
>     <array-item>
>       <key>name</key>
>       <value>greeter</value>
>     </array-item>
>     <array-item>
>       <key>label</key>
>       <value h:translate>Hello World</value>
>     </array-item>
>   </array>
> </document>
> 
bash
## Parse and re-print an improvised PHP snippet
echo ' return [1,2,3];' | ./scripts/reprint.php

## Tokenize an improvised PHP snippet
echo ' return [1,2,3];' | ./scripts/tokenize.php

## Parse an improvised PHP snippet
echo ' return [1,2,3];' | ./scripts/parse.php
bash
## Parse and re-print a PHP file
cat examples/simple-array-7.4.php | ./scripts/reprint.php | less

## Tokenize a PHP file
cat examples/simple-array-7.4.php | ./scripts/tokenize.php | less

## Parse a PHP file
cat examples/simple-array-7.4.php | ./scripts/parse.php | less