PHP code example of s9e / bencode

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

    

s9e / bencode example snippets


use s9e\Bencode\Bencode;
print_r(Bencode::decode('d3:bar4:spam3:fooi42ee'));

use s9e\Bencode\Bencode;
print_r(Bencode::encode(['foo' => 42, 'bar' => 'spam']));

use s9e\Bencode\Bencode;
use s9e\Bencode\BencodeSerializable;

$bencodable = new class implements BencodeSerializable
{
	public function bencodeSerialize(): array|int|string
	{
		return 42;
	}
};

print_r(Bencode::encode($bencodable));

try
{
	s9e\Bencode\Bencode::decode('i123x');
}
catch (s9e\Bencode\Exceptions\DecodingException $e)
{
	var_dump($e->getMessage(), $e->getOffset());
}

try
{
	s9e\Bencode\Bencode::encode(2.5);
}
catch (s9e\Bencode\Exceptions\EncodingException $e)
{
	var_dump($e->getMessage(), $e->getValue());
}

use s9e\Bencode\Bencode;

$input = 'd3:fooi42e3:bar4:spame';
try
{
	$value = Bencode::decode($input);
}
catch (s9e\Bencode\Exceptions\ComplianceError $e)
{
	echo 'Failed: ', $e->getMessage(), "\nRetry with non-compliant decoder:\n";

	$value = Bencode::decodeNonCompliant($input);
	print_r($value);
}