Skip to content

Working with JSON

Greg Bowler edited this page Mar 28, 2023 · 3 revisions

Combining JSON with Curl is such a common task for web developers, the PHP.Gt/Json library is bundled by default, which allows you to work with JSON requests and responses in a type-safe way.

Where Curl::output() returns a string representation of the HTTP response body, Curl::outputJson() returns a well-formed JsonObject that can be traversed with type safety.

Here's an example that makes a request to the https://catfact.ninja/ API, then echoes the data and it receives as a string and an int:

use Gt\Curl\Curl;

$curl = new Curl("https://catfact.ninja/fact");
$curl->exec();
$json = $curl->outputJson();
echo "Here's a cat fact: " . $json->getString("fact");
echo PHP_EOL;
echo "The fact's length is " . $json->getInt("length") . " characters.";
echo PHP_EOL;

To learn more about the different ways you can work with JSON, take a look at https://www.php.gt/json.


Next up, learn how to execute multiple concurrent curl requests.

Clone this wiki locally