PHPackages                             nextgenswitch/nextgenswitch-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. nextgenswitch/nextgenswitch-php

ActiveLibrary

nextgenswitch/nextgenswitch-php
===============================

Official PHP SDK for the NextGenSwitch Programmable Voice API and Voice XML.

V1.0.0(2y ago)027PHP

Since Apr 24Pushed 1y ago1 watchersCompare

[ Source](https://github.com/nextgenswitch/nextgenswitch-php)[ Packagist](https://packagist.org/packages/nextgenswitch/nextgenswitch-php)[ RSS](/packages/nextgenswitch-nextgenswitch-php/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (1)DependenciesVersions (5)Used By (0)

NextGenSwitch PHP SDK
=====================

[](#nextgenswitch-php-sdk)

[![Tests](https://github.com/nextgenswitch/nextgenswitch-php/actions/workflows/tests.yml/badge.svg)](https://github.com/nextgenswitch/nextgenswitch-php/actions/workflows/tests.yml)[![PHP](https://camo.githubusercontent.com/c0761d101b201f2531c8037e6264420e2e43705d3776a9fcfb70c8cf3d3563a3/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312532422d3737374242342e737667)](https://www.php.net/)[![License: MIT](https://camo.githubusercontent.com/08cef40a9105b6526ca22088bc514fbfdbc9aac1ddbf8d4e6c750e3a88a44dca/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c75652e737667)](LICENSE)

The official PHP SDK for the [NextGenSwitch Programmable Voice API](https://nextgenswitch.com/docs/programmable-voice-api/). Create and modify calls, build escaped Voice XML, stream call audio to AI services, and parse Gather and Dial callbacks with typed PHP objects.

Requirements
------------

[](#requirements)

- PHP 8.1 or newer
- DOM extension
- Composer
- A NextGenSwitch deployment and API credentials

Installation
------------

[](#installation)

```
composer require nextgenswitch/nextgenswitch-php
```

Configure the Client
--------------------

[](#configure-the-client)

Keep credentials in environment variables or a secret manager.

```
use NextGenSwitch\Client;

$client = new Client(
    baseUrl: getenv('NEXTGENSWITCH_BASE_URL'),
    authorizationCode: getenv('NEXTGENSWITCH_AUTHORIZATION'),
    authorizationSecret: getenv('NEXTGENSWITCH_AUTHORIZATION_SECRET'),
);
```

The SDK sends credentials with the `X-Authorization` and `X-Authorization-Secret` headers documented by NextGenSwitch. Use HTTPS for remote deployments.

Create a Call
-------------

[](#create-a-call)

Use either inline Voice XML or a URL that returns a valid ``.

```
use NextGenSwitch\VoiceResponse;

$voice = (new VoiceResponse())
    ->say('Welcome to NextGenSwitch.')
    ->gather(
        [
            'action' => 'https://example.com/gather',
            'method' => 'POST',
            'numDigits' => 1,
            'timeout' => 10,
        ],
        static fn ($gather) => $gather->say('Press one for sales.'),
    );

$result = $client->createCall(
    to: '2001',
    from: '1001',
    responseXml: $voice,
    statusCallback: 'https://example.com/call-status',
);

$call = $result->data();
```

To use a hosted XML document:

```
$result = $client->createCall(
    to: '2001',
    from: '1001',
    responseUrl: 'https://example.com/call-flow.xml',
);
```

Exactly one of `responseXml` or `responseUrl` is required.

Modify an Active Call
---------------------

[](#modify-an-active-call)

```
$updatedFlow = (new VoiceResponse())
    ->pause(2)
    ->say('Your call flow has been updated.')
    ->dial('1000');

$client->modifyCall('CALL-123', $updatedFlow);
```

Build Voice XML
---------------

[](#build-voice-xml)

```
$response = (new VoiceResponse())
    ->say('This is a test.', ['loop' => 2])
    ->play('https://example.com/audio.mp3', ['loop' => 1])
    ->record([
        'action' => 'https://example.com/recording',
        'method' => 'POST',
        'timeout' => 5,
        'finishOnKey' => '#',
        'beep' => true,
    ])
    ->hangup();

header('Content-Type: application/xml; charset=UTF-8');
echo $response->xml();
```

Supported helpers match the official API documentation:

XML verbSDK method```say($text, $attributes)````play($url, $attributes)````gather($attributes, $children)````dial($to, $attributes, $children)````record($attributes)````stream($url, $parameters, $attributes)````hangup()````pause($seconds)````redirect($url, $method)````bridge($callId, $bridgeAfterEstablish)````leave()`Text and attribute values are encoded through PHP's DOM implementation instead of string concatenation.

Stream Audio to an AI Service
-----------------------------

[](#stream-audio-to-an-ai-service)

```
$response = (new VoiceResponse())->stream(
    url: 'wss://voice.example.com/session',
    parameters: [
        'session_id' => 'session-123',
        'tenant' => 'example',
    ],
    attributes: ['name' => 'assistant-stream'],
);
```

Do not put provider API keys in Voice XML. Resolve secrets on the WebSocket service.

Parse Action Callbacks
----------------------

[](#parse-action-callbacks)

```
use NextGenSwitch\Webhook\GatherResult;

$gather = GatherResult::fromArray($_POST);

if ($gather->digits === '1') {
    echo (new VoiceResponse())->dial('1001')->xml();
} else {
    echo (new VoiceResponse())->say('No valid selection received.')->hangup()->xml();
}
```

Dial callbacks can be parsed with `DialResult::fromArray($_POST)`. Its `established`, `duration`, `waitingDuration`, `bridgeCallId`, and `recordFile` properties correspond to the documented callback fields.

Callback authenticity controls are deployment-specific and are not currently documented as a NextGenSwitch signature scheme. Restrict callback endpoints, require TLS, validate expected fields, and apply your own authentication controls where supported.

Errors
------

[](#errors)

- `ValidationException`: invalid SDK input before a request is sent
- `ApiException`: a non-2xx API response; exposes `statusCode()` and `responseBody()`
- `NextGenSwitchException`: transport or other SDK failure

```
use NextGenSwitch\Exception\ApiException;

try {
    $client->modifyCall('CALL-123', (new VoiceResponse())->hangup());
} catch (ApiException $error) {
    error_log($error->statusCode() . ': ' . $error->getMessage());
}
```

Runnable Examples
-----------------

[](#runnable-examples)

After `composer install`, configure credentials without committing them:

```
export NEXTGENSWITCH_BASE_URL="https://your-switch.example.com"
export NEXTGENSWITCH_AUTHORIZATION="your-authorization-code"
export NEXTGENSWITCH_AUTHORIZATION_SECRET="your-authorization-secret"
```

Then run or adapt these examples:

ExamplePurpose[`create-call.php`](examples/create-call.php)Create a call with inline Gather instructions[`modify-call.php`](examples/modify-call.php)Replace the flow of an active call by call ID[`record-call.php`](examples/record-call.php)Record caller audio with beep, transcription, trimming, and callback[`dial-with-recording.php`](examples/dial-with-recording.php)Dial an external destination and record from answer[`stream-to-ai-agent.php`](examples/stream-to-ai-agent.php)Stream bidirectional audio to a WebSocket AI service[`gather-webhook.php`](examples/gather-webhook.php)Parse Gather input and return the next Voice XML flow[`dial-webhook.php`](examples/dial-webhook.php)Parse Dial completion and return follow-up Voice XMLFor example:

```
php examples/create-call.php
php examples/record-call.php
php examples/modify-call.php CALL-123
```

Replace all `example.com` callback, media, and WebSocket URLs with TLS endpoints you control. Validate callback input and never commit API or SIP credentials.

Development
-----------

[](#development)

```
composer install
composer validate --strict
composer lint
composer test
```

The test workflow covers PHP 8.1, 8.2, 8.3, and 8.4.

Documentation and Support
-------------------------

[](#documentation-and-support)

- [Programmable Voice API](https://nextgenswitch.com/docs/programmable-voice-api/)
- [NextGenSwitch documentation](https://nextgenswitch.com/docs/)
- [NextGenSwitch website](https://nextgenswitch.com/)
- [Report an SDK issue](https://github.com/nextgenswitch/nextgenswitch-php/issues)
- [Contact NextGenSwitch](https://nextgenswitch.com/contact/)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

25

—

LowBetter than 35% of packages

Maintenance28

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

846d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/70337001?v=4)[Rakib Uddin Ahmed](/maintainers/infosoftbd)[@InfoSoftBD](https://github.com/InfoSoftBD)

---

Top Contributors

[![masum0009](https://avatars.githubusercontent.com/u/1522362?v=4)](https://github.com/masum0009 "masum0009 (2 commits)")

### Embed Badge

![Health badge](/badges/nextgenswitch-nextgenswitch-php/health.svg)

```
[![Health](https://phpackages.com/badges/nextgenswitch-nextgenswitch-php/health.svg)](https://phpackages.com/packages/nextgenswitch-nextgenswitch-php)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
