PHP code example of fortephp / forte

1. Go to this page and download the library: Download fortephp/forte library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fortephp / forte example snippets


use Forte\Facades\Forte;
use Forte\Rewriting\NodePath;

// Parse a Blade template into a document
$doc = Forte::parse('<div class="mt-4">Hello, {{ $name }}!</div>');

// Query with XPath
$divs = $doc->xpath('//div[@class]')->get();

// Rewrite (returns a new document, original is unchanged)
$newDoc = $doc->rewriteWith(function (NodePath $path) {
    if ($path->isTag('div')) {
        $path->removeClass('mt-4');
        $path->addClass('container');
    }
});

echo $newDoc->render(); // <div class="container">Hello, {{ $name }}!</div>

$doc = Forte::parse($bladeTemplate);
$doc = Forte::parseFile('resources/views/welcome.blade.php');

use Forte\Ast\TraversalOptions;

// Lazy, fluent collections with optional name filters
$forms = $doc->queryElements('form');
$conditionals = $doc->queryBlockDirectives(['if', 'unless']);
$components = $doc->queryComponents(['x-alert', 'livewire:*']);

// Fast exact lookups and convenient existence checks
$navigation = $doc->elementById('primary-navigation');
$hasHead = $doc->hasElement('head');

// Attribute semantics live on Attribute; ElementNode provides null-safe proxies
$form = $doc->firstElement('form');
$method = $form?->attribute('method');
$isDynamic = $method?->isDynamic() ?? false;
$staticMethod = $form?->staticAttributeValueLower('method');
$classes = $form?->attributeTokens('class') ?? [];

// Navigate relationships without rebuilding ancestor/descendant loops
$owner = $navigation?->closestElement('header');
$links = $navigation?->descendantElements('a');

// Include attribute/tag-name internals when a deep semantic scan is needed
$allEchoes = $doc->allEchoes(TraversalOptions::deep());

// XPath
$doc->xpath('//forte:if')->get();

$doc->rewriteWith(function (NodePath $path) {
    if ($path->isTag('center')) {
        $path->renameTag('div');
        $path->addClass('text-center');
    }
});

$component = $doc->findComponentByName('x-alert');
$directive = $doc->find(fn ($n) => $n->isDirectiveNamed('foreach'));

use Forte\Rewriting\Builders\Builder;

Builder::element('div')->class('wrapper')->text('Hello');
Builder::directive('if', '($show)');
Builder::echo('$name');