PHP code example of noresources / ns-php-mediatype

1. Go to this page and download the library: Download noresources/ns-php-mediatype 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/ */

    

noresources / ns-php-mediatype example snippets



use NoreSources\MediaType\MediaType;
use NoreSources\MediaType\MediaTypeFactory;
use NoreSources\MediaType\MediaRange;

$factory = MediaTypeFactory::getInstance ();
$mediaType = $factory->createFromString ('text/vnd.noresources.incredibly.flexible+xml');

var_dump ($mediaType->getMainType()); i       // "text"
var_dump ($mediaType->getStructuredSyntax()); // "xml"

$subType = $mediaType->getSubType ();
var_dump (\strval ($subType));                // "vnd.noresources.incredibly.flexible+xml"
var_dump ($subType->getFacets());             // [ "vnd", "noresources", "incredibly", "flexible" ]


// From a file or a stream
$mediaType = $factory->createFromMedia ('path/to/filename.html');
var_dump (\strval ($mediaType)); // "text/html"

// Media range is also recognized
$range = $factory->createFromString ('image/*');

// Comparing
$html = $factory->createFromString ('text/html');
$anyText = $factory->createFromString ('text/*');
$any = $factory->createFromString ('*/*');

var_dump ([
	'text/html vs text/*' => MediaRange::compare ($html, $anyText),
	'text/* vs */*' => MediaRange::compare ($anyText, $any),
	'*/* vs text/html' => MediaRange::compare ($any, $html)
]);

/* 
array(3) {
  ["text/html vs text/*"]=> int(1)
  ["text/* vs */*"]=> int(1)
  ["*/* vs text/html"]=> int(-1)
}
*/