Skip to main content

Confirm

Are you sure?

PHP · Code recipe

Get the rendered HTML of a JavaScript page in PHP

Fetch the HTML a browser ends up with, JavaScript and all, in PHP 8.1+ with the curl extension. Every program on this page runs as it stands — each one was run against a stub of the API before it was published.

By · Last updated: September 2026

TL;DR

To get the HTML of a JavaScript-rendered page in PHP, POST its URL to https://urlpipe.dev/html with sync set to true. The body is the DOM after the page's scripts ran in real Chrome, serialized as HTML — what a visitor's browser holds, not what the server first sent — read with curl_exec with CURLOPT_RETURNTRANSFER, for 1 credit.

Free plan, no credit card. 1,000 credits a month.

One POST to /html loads the page in real Chrome, lets its JavaScript run, and serializes the DOM it ended up with. For a single-page app that is the difference between an empty <div id="root"> and the content; the rendered vs raw HTML guide shows how far apart the two get.

The body is the HTML as text, read with curl_exec with CURLOPT_RETURNTRANSFER. The program saves it and reports its size in bytes — compare that with curl -s https://example.com | wc -c and you see how much of the page only exists after the scripts ran.

Setup

Before you start

Nothing to install beyond PHP itself: the curl extension ships with it. Check it is loaded, and put your API key in the environment.

Terminal
php -m | grep curl   # prints "curl"
export URLPIPE_API_KEY="your_api_key"

The request

Save the rendered HTML and report its size

Without CURLOPT_RETURNTRANSFER, curl_exec() prints the body and returns true — the most common reason a PHP example "returns nothing". curl_exec() returns false only when there was no HTTP answer at all; a 422 is still a string, so read the status too. strlen() counts bytes, not characters, which is the size you want here.

rendered_html.php
<?php

function fail(string $message): never
{
    fwrite(STDERR, $message . "\n");
    exit(1);
}

$ch = curl_init("https://urlpipe.dev/html");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    // Return the body from curl_exec() instead of printing it.
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("URLPIPE_API_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode(["url" => "https://example.com", "sync" => true]),
    // A sync call can take up to 60 s; curl would otherwise wait forever.
    CURLOPT_TIMEOUT => 90,
]);
$body = curl_exec($ch);
if ($body === false) {
    fail("Request failed: " . curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status !== 200) {
    fail("URLpipe answered {$status}: {$body}");
}

file_put_contents("page.html", $body);
echo "Saved page.html (" . strlen($body) . " bytes)\n";

Run it: php rendered_html.php

Async

The async variant: a token, a webhook and a poll

Leave out sync and the answer is a token, straight away. send() uses CURLOPT_CUSTOMREQUEST so one function makes both the POST and the GETs, and array destructuring ([$status, $body] = …) keeps the loop short.

rendered_html_async.php
<?php

const API = "https://urlpipe.dev";

function fail(string $message): never
{
    fwrite(STDERR, $message . "\n");
    exit(1);
}

// One request to the API: returns [status, body].
function send(string $method, string $path, ?array $payload = null): array
{
    $ch = curl_init(API . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer " . getenv("URLPIPE_API_KEY"),
            "Content-Type: application/json",
        ],
        CURLOPT_TIMEOUT => 30,
    ]);
    if ($payload !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    }
    $body = curl_exec($ch);
    if ($body === false) {
        fail("Request failed: " . curl_error($ch));
    }
    return [curl_getinfo($ch, CURLINFO_RESPONSE_CODE), $body];
}

// No "sync": the request is accepted at once and the work carries on without you.
[$status, $body] = send("POST", "/html", [
    "url" => "https://example.com",
    "report_to" => "https://your-app.com/webhooks/urlpipe",
    "labels" => ["customer" => "acme"],
]);
if ($status !== 200) {
    fail("URLpipe answered {$status}: {$body}");
}
$token = json_decode($body, true)["token"];
echo "Accepted {$token}\n";

// The result is POSTed to report_to when it is ready. Polling by token is the
// other way to collect it: no endpoint needed, and a backup for the webhook.
for ($attempt = 0; $attempt < 60; $attempt++) {
    [$status, $body] = send("GET", "/result/{$token}");
    if ($status !== 202) { // 202 means still processing
        break;
    }
    sleep(2);
}
if ($status === 202) {
    fail("Still processing after two minutes; try the token again later.");
}
if ($status === 422) {
    fail("The analysis failed: " . json_decode($body, true)["error"]);
}
if ($status === 410) {
    fail("The result is past the 30-day window; send the request again.");
}
if ($status !== 200) {
    fail("URLpipe answered {$status}: {$body}");
}

file_put_contents("page.html", $body);
echo "Saved page.html (" . strlen($body) . " bytes)\n";

Run it: php rendered_html_async.php

Errors

Handle errors and retries

json_decode() returns null for a body that is not JSON (a 401 answers in plain text), and ?: [] turns that into an empty array. CURLOPT_HEADERFUNCTION is how curl hands you response headers one line at a time.

rendered_html_errors.php
<?php

final class URLpipeError extends RuntimeException
{
}

// POST a sync request and return the result body, or throw URLpipeError.
function urlpipe(string $path, array $payload, int $attempts = 5): string
{
    for ($attempt = 0; $attempt < $attempts; $attempt++) {
        $headers = [];
        $ch = curl_init("https://urlpipe.dev{$path}");
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                "Authorization: Bearer " . getenv("URLPIPE_API_KEY"),
                "Content-Type: application/json",
            ],
            CURLOPT_POSTFIELDS => json_encode($payload + ["sync" => true]),
            CURLOPT_TIMEOUT => 90,
            // Collect the response headers: Retry-After is the one needed here.
            CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$headers): int {
                [$name, $value] = array_pad(explode(":", $line, 2), 2, "");
                $headers[strtolower(trim($name))] = trim($value);
                return strlen($line);
            },
        ]);
        $body = curl_exec($ch);
        if ($body === false) {
            throw new URLpipeError("network error: " . curl_error($ch));
        }
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($status === 200) {
            return $body;
        }
        if ($status === 401) {
            throw new URLpipeError("401: the API key is missing or wrong. Check URLPIPE_API_KEY.");
        }

        $error = json_decode($body, true) ?: [];
        $code = $error["error"] ?? "";
        $detail = isset($error["message"]) ? "{$code}: {$error["message"]}" : $code;

        if ($status === 429 && $code === "rate_limited") {
            // Sending too fast: Retry-After says how long the window has left.
            sleep((int) ($headers["retry-after"] ?? 1));
        } elseif ($status === 429 && $code === "concurrency_limit") {
            // Every parallel slot on your plan is busy with your own requests.
            sleep(2 ** $attempt);
        } elseif ($status === 504) {
            // Still running on our side; the token collects it from GET /result/:token.
            throw new URLpipeError("504 processing_timeout: collect it later with token {$error["token"]}");
        } else {
            // 403 email_unverified, 422 (a bad parameter, or a page that would not load),
            // 429 quota_exceeded: sending the same request again gets the same answer.
            throw new URLpipeError("{$status}: {$detail}");
        }
    }
    throw new URLpipeError("429: still refused after {$attempts} attempts");
}

try {
    $body = urlpipe("/html", ["url" => "https://example.com"]);
} catch (URLpipeError $e) {
    fwrite(STDERR, "URLpipe: {$e->getMessage()}\n");
    exit(1);
}

file_put_contents("page.html", $body);
echo "Saved page.html (" . strlen($body) . " bytes)\n";

Run it: php rendered_html_errors.php

Details

What to know about /html

  • The HTML is serialized from the live DOM, so it is well-formed but not byte-identical to any file on the server.
  • Pages over 10 MB of HTML are refused with The page is too big to be processed.
  • page_options.wait_for_selector waits for an element that loads late; delay waits a fixed time on top.
  • It is the whole document, scripts and styles included, not a cleaned-up version of it. For clean text, use Markdown instead.

Other languages

Get the rendered HTML of a JavaScript page in another language

More PHP: every PHP recipe

FAQ

Frequently asked questions

How is this different from fetching the URL myself?
A plain GET returns what the server sent before any JavaScript ran. /html returns the DOM after the page's scripts ran in real Chrome — the HTML a visitor's browser actually holds.
Can I wait for content that loads late?
Yes: page_options.wait_for_selector waits up to 10 seconds for an element to appear, and delay adds a fixed wait. If the element never appears the request is a 422 and costs nothing.
Does URLpipe follow robots.txt?
Yes, by default, for every project. You can turn it off per project, and then you are responsible for having the right to fetch those pages.
Do I need an SDK to call URLpipe from PHP?
No Composer package: the curl extension is part of PHP, and the API is one POST per job.

Get a key and run it.

Free plan, no card. Paste your key into URLPIPE_API_KEY and every program on this page runs as it is.