PHP code example of nilportugues / xml
1. Go to this page and download the library: Download nilportugues/xml 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/ */
nilportugues / xml example snippets
$post = new Post(
new PostId(9),
'Hello World',
'Your first post',
new User(
new UserId(1),
'Post Author'
),
[
new Comment(
new CommentId(1000),
'Have no fear, sers, your king is safe.',
new User(new UserId(2), 'Barristan Selmy'),
[
'created_at' => (new DateTime('2015/07/18 12:13:00'))->format('c'),
'accepted_at' => (new DateTime('2015/07/19 00:00:00'))->format('c'),
]
),
]
);
use NilPortugues\Api\Mapping\Mapper;
$mappings = [
[
'class' => Post::class,
'alias' => 'Message',
'aliased_properties' => [
'author' => 'author',
'title' => 'headline',
'content' => 'body',
],
'hide_properties' => [
],
'id_properties' => [
'postId',
],
'urls' => [
'self' => 'http://example.com/posts/{postId}',
'comments' => 'http://example.com/posts/{postId}/comments'
],
],
[
'class' => PostId::class,
'alias' => '',
'aliased_properties' => [],
'hide_properties' => [],
'id_properties' => [
'postId',
],
'urls' => [
'self' => 'http://example.com/posts/{postId}',
],
],
[
'class' => User::class,
'alias' => '',
'aliased_properties' => [],
'hide_properties' => [],
'id_properties' => [
'userId',
],
'urls' => [
'self' => 'http://example.com/users/{userId}',
'friends' => 'http://example.com/users/{userId}/friends',
'comments' => 'http://example.com/users/{userId}/comments',
],
],
[
'class' => UserId::class,
'alias' => '',
'aliased_properties' => [],
'hide_properties' => [],
'id_properties' => [
'userId',
],
'urls' => [
'self' => 'http://example.com/users/{userId}',
'friends' => 'http://example.com/users/{userId}/friends',
'comments' => 'http://example.com/users/{userId}/comments',
],
],
[
'class' => Comment::class,
'alias' => '',
'aliased_properties' => [],
'hide_properties' => [],
'id_properties' => [
'commentId',
],
'urls' => [
'self' => 'http://example.com/comments/{commentId}',
],
],
[
'class' => CommentId::class,
'alias' => '',
'aliased_properties' => [],
'hide_properties' => [],
'id_properties' => [
'commentId',
],
'urls' => [
'self' => 'http://example.com/comments/{commentId}',
],
],
];
$mapper = new Mapper($mappings);
use NilPortugues\Api\Xml\XmlSerializer;
use NilPortugues\Api\Xml\Http\Message\Response;
$serializer = new XmlSerializer($mapper);
$output = $serializer->serialize($post);
//PSR7 Response with headers and content.
$response = new Response($output);
header(
sprintf(
'HTTP/%s %s %s',
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
)
);
foreach($response->getHeaders() as $header => $values) {
header(sprintf("%s:%s\n", $header, implode(', ', $values)));
}
echo $response->getBody();