# PHP examples — `posprint_url()`

See [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md) for URL format and size limits.

```php
require __DIR__ . '/posprint_url.php';
```

## From an array

Build the `.pos` document in PHP and pass an associative array:

```php
$url = posprint_url([
    'version' => 1,
    'metadata' => [
        'title' => 'Barcode demo',
        'page_width_mm' => 53.0,
        'chars_per_line' => 32,
    ],
    'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
]);

echo $url, "\n";
// posprint://print?v=1&d=…
```

Use in HTML:

```php
<a href="<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>">Print receipt</a>
```

## From a local `.pos` file

Read the file as JSON text and pass the string (same encoding path as an array):

```php
$path = __DIR__ . '/../../examples/url-demo.pos';
$json = file_get_contents($path);
if ($json === false) {
    throw new RuntimeException("Could not read {$path}");
}

// Optional: strip UTF-8 BOM if present (Windows editors)
$json = preg_replace('/^\xEF\xBB\xBF/', '', $json) ?? $json;

$url = posprint_url($json);
echo $url, "\n";
```

Or decode first to validate, then encode:

```php
$doc = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
$url = posprint_url($doc);
```

## Length warning

On Windows, keep the full URL under ~7000 characters so the OS can launch posprint. For large templates, keep images as `@image https://…` in the body instead of embedding bytes in JSON.
