Encoding ######## .. highlight:: php .. versionchanged:: 2.0 options array is replaced with named parameters .. note:: Parameter order is not guaranteed for options, use named parameters Scalars and arrays ================== .. versionchanged:: 4.1 floats now throw an exception instead of becoming strings :: [1,2,3,4], // integer is stored as is 'int' => 123, // true will be an integer 1 'true' => true, // false and null values will be skipped 'false' => false, // string can contain any binary data 'string' => "test\0test", ]); // "d" . // "3:arr" . "l" . "i1e" . "i2e" . "i3e" . "i4e" . "e" . // "3:int" . "i123e" . // "6:string" . "9:test\0test" . // "4:true" . "i1e" . // "e" Objects ======= ArrayObject and stdClass ------------------------ .. versionchanged:: 3.0 ``Traversable`` objects no longer become dictionaries automatically ArrayObject and stdClass become dictionaries:: a = '123'; $std->b = 456; $encoded = Bencode::encode($std); // "d1:a3:1231:bi456ee" Big integer support ------------------- .. versionadded:: 1.5/2.5 GMP support .. versionadded:: 1.6/2.6 Pear's Math_BigInteger, brick/math, BigIntType support .. note:: More in the :ref:`decoding section ` GMP object, Pear's Math_BigInteger, brick/math BigInteger, and internal type BigIntType (simple numeric string wrapper) will become integers:: gmp_pow(2, 96), 'brick' => BigInteger::of(2)->power(96), 'pear' => (new Math_BigInteger(1))->bitwise_leftShift(96), 'internal' => new BigIntType('7922816251426433759354395033'), ]); // "d5:bricki79228162514264337593543950336e3:gmpi792..." Stringable ---------- .. versionchanged:: 3.0 ``Stringable`` objects no longer become strings automatically You can convert ``Stringable`` objects to strings using ``useStringable`` option:: 'value1'; yield 'key2' => 'value2'; })() )); // "d4:key16:value14:key26:value2e" BencodeSerializable ------------------- .. versionadded:: 1.2 .. versionadded:: 1.7/2.7/3.0 ``JsonSerializable`` handling You can also force object representation by implementing BencodeSerializable interface. This will work exactly like JsonSerializable_ interface:: static::class, 'name' => 'myfile.torrent', 'size' => 5 * 1024 * 1024, ]; } } $file = new MyFile; $encoded = Bencode::encode($file); // "d5:class6:MyFile4:name14:myfile.torrent4:sizei5242880ee" Optionally you can use JsonSerializable_ itself too:: static::class, 'name' => 'myfile.torrent', 'size' => 5 * 1024 * 1024, ]; } } $file = new MyFile; $encoded = Bencode::encode( $file, useJsonSerializable: true, ); // "d5:class6:MyFile4:name14:myfile.torrent4:sizei5242880ee" Working with files ================== .. versionchanged:: 3.0 ``($filename, $data)`` → ``($data, $filename)`` Save data to file:: encode($data); $encoder->encodeToStream($data, $stream); $encoder->dump($data, $filename); .. _JsonSerializable: http://php.net/manual/en/class.jsonserializable.php