diff --git a/README.md b/README.md index 3f4b46e..61f6ad0 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,8 @@ $response = $http->sendRequest($fastRequest); $http->wait(); ``` +For more extensive examples, check out the code in the [example directory](/example). + [psr-7]: http://www.php-fig.org/psr/psr-7/ [fetch-standard]: https://fetch.spec.whatwg.org/ [fetch-js]: https://developer.mozilla.org/en/docs/Web/API/Fetch_API diff --git a/example/02-post-request.php b/example/02-post-request.php new file mode 100644 index 0000000..66606ca --- /dev/null +++ b/example/02-post-request.php @@ -0,0 +1,47 @@ +fetch("https://postman-echo.com/post", [ +// All of the request parameters can be passed directly here, or alternatively +// the fetch() function can take a PSR-7 RequestInterface object. + "method" => "POST", + "headers" => [ + "Content-Type" => "application/x-www-form-urlencoded", + ], + "body" => http_build_query([ + "name" => "Mark Zuckerberg", + "dob" => "1984-05-14", + "email" => "zuck@fb.com", + ]), +]) +->then(function(BodyResponse $response) { + if(!$response->ok) { + echo "Error posting to Postman Echo." . PHP_EOL; + exit; + } +// Postman Echo servers respond with a JSON representation of the request +// that was received. + return $response->json(); +}) +->then(function($json) { + echo "The Postman Echo server received the following form fields:"; + echo PHP_EOL; + + foreach($json->form as $key => $value) { + echo "$key = $value" . PHP_EOL; + } +}); + +// To execute the above Promise(s), call wait() or all(). +$http->wait(); \ No newline at end of file