PHP code example of ayeaye / formatters

1. Go to this page and download the library: Download ayeaye/formatters 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/ */

    

ayeaye / formatters example snippets


use AyeAye\Formatter\Writer\Json;

$data = ['boolean' => true];

$json = new Json();
echo $json->format($data); // {"boolean":true}

use AyeAye\Formatter\Writer\Xml;

$data = ['boolean' => true];

$xml = new Xml();
echo $xml->format($data); // <?xml version="1.0" encoding="UTF-8" 

use AyeAye\Formatter\FormatFactory;
use AyeAye\Formatter\Writer\Json;

$formatFactory = new FormatFactory([
    'json' => new Json(),                    // Instantiate
    'xml' => 'AyeAye\Formatter\Writer\Xml', // or don't
]);

$formatFactory->getFormatterFor('json'); // returns the same Json instance every time.
$formatFactory->getFormatterFor('xm'); // returns a new XML instance every time.

use AyeAye\Formatter\FormatFactory;
use AyeAye\Formatter\Writer\Json;
use AyeAye\Formatter\Writer\Xml;

$xmlFormatter = new Xml();
$jsonFormatter = new Json();
$this->formatFactory = new FormatFactory([
    // xml
    'xml' => $xmlFormatter,
    'text/xml' => $xmlFormatter,
    'application/xml' => $xmlFormatter,
    // json
    'json' => $jsonFormatter,
    'application/json' => $jsonFormatter,
]);

$formatFactory->getFormatterFor([
    $_HEADER['Accepts'], // The header that requests a specific format
    getRequestSuffix(),  // A result of looking at suffix of the requested resource
    'json',              // A fallback option
]);