Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Html Converter Laravel Package

bicpi/html-converter

PHP library for converting HTML to plain text, ideal for generating text parts of HTML emails. Includes Simple (strip_tags), Lynx (best results, keeps links), Html2Text, and Chain converter to pick the first available backend.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bicpi/html-converter
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Convert a simple HTML string to plain text:

    use Bicpi\HtmlConverter\HtmlConverter;
    
    $html = '<h1>Hello World</h1><p>This is <strong>HTML</strong>.</p>';
    $converter = new HtmlConverter();
    $text = $converter->convert($html);
    
    // Output: "Hello World\n\nThis is HTML."
    
  3. Where to Look First:

    • README for basic usage.
    • src/HtmlConverter.php for core logic and available methods.
    • No config file is needed; the package is self-contained.

Implementation Patterns

Core Workflows

  1. Basic Conversion:

    $converter = new HtmlConverter();
    $text = $converter->convert($htmlString);
    
    • Handles common tags (<h1><h6>, <p>, <strong>, <em>, <a>, etc.).
    • Preserves line breaks and spacing logically (e.g., <h1> → newline, <p> → double newline).
  2. Customizing Output:

    • Link Handling: Extract URLs from <a> tags:
      $converter->setLinkHandler(function ($url, $text) {
          return "[{$text}]({$url})";
      });
      
    • Tag Whitelisting: Allow/block specific tags:
      $converter->setAllowedTags(['h1', 'h2', 'p', 'ul', 'li']);
      
  3. Integration with Laravel:

    • Service Provider Binding (optional):
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(HtmlConverter::class);
      }
      
    • Usage in Controllers/Blade:
      use Bicpi\HtmlConverter\HtmlConverter;
      
      public function showTextVersion(Request $request)
      {
          $html = $request->input('html_content');
          $text = app(HtmlConverter::class)->convert($html);
          return response()->json(['text' => $text]);
      }
      
  4. Batch Processing:

    $htmlStrings = [/* array of HTML strings */];
    $converter = new HtmlConverter();
    $texts = array_map([$converter, 'convert'], $htmlStrings);
    
  5. Edge Cases:

    • Nested Tags: Handles <strong><em>text</em></strong>text (bold + italic).
    • Scripts/Styles: Strips <script> and <style> by default (configurable via setAllowedTags).

Gotchas and Tips

Pitfalls

  1. Line Break Sensitivity:

    • The converter uses \n for newlines. If your system expects <br> or <br/> to be preserved, manually replace them:
      $text = str_replace(['<br>', '<br/>'], "\n", $html) ?? $html;
      $text = $converter->convert($text);
      
    • Fix: Override the handleBrTag method in a subclass if needed.
  2. URL Handling:

    • Links (<a>) default to [text](url). If you need raw URLs:
      $converter->setLinkHandler(function ($url) {
          return $url;
      });
      
    • Gotcha: Malformed URLs (e.g., <a href="javascript:alert()">) may break. Sanitize input first:
      $html = filter_var($html, FILTER_SANITIZE_URL, FILTER_FLAG_NO_ENCODE);
      
  3. Performance:

    • Avoid instantiating HtmlConverter per request in high-traffic apps. Use Laravel’s service container (see Implementation Patterns).
    • Tip: Cache converted results if the same HTML repeats (e.g., email templates).
  4. Whitelisting Quirks:

    • setAllowedTags([]) strips all HTML. Use cautiously.
    • Workaround: Extend the class to add dynamic tag rules:
      class CustomConverter extends HtmlConverter {
          public function __construct() {
              $this->setAllowedTags(['div', 'span']); // Example
          }
      }
      

Debugging Tips

  1. Inspect Intermediate Steps:

    • Enable debug mode to see stripped tags:
      $converter->setDebug(true);
      $text = $converter->convert($html);
      // Check $converter->getDebugOutput() for details.
      
  2. Test Edge Cases:

    • Table Tags: <table>, <tr>, <td> are stripped by default. Add them to setAllowedTags() if needed.
    • Custom Attributes: Non-standard attributes (e.g., data-*) are ignored. Use setAttributeHandler to customize:
      $converter->setAttributeHandler(function ($tag, $attributes) {
          return array_filter($attributes, fn($k) => str_starts_with($k, 'data-'), ARRAY_FILTER_USE_KEY);
      });
      
  3. Character Encoding:

    • Ensure input HTML is UTF-8. Use mb_convert_encoding() if needed:
      $html = mb_convert_encoding($html, 'UTF-8', 'auto');
      

Extension Points

  1. Custom Tag Handlers:

    • Override handleTag() to process tags uniquely:
      $converter->setTagHandler('code', function ($text) {
          return '`' . $text . '`';
      });
      
  2. Pre/Post-Processing:

    • Chain with Laravel’s Str::of() or Str::limit() for truncation:
      use Illuminate\Support\Str;
      
      $text = Str::of($converter->convert($html))->limit(200);
      
  3. Output Formatting:

    • Use setTextHandler() to modify the final text:
      $converter->setTextHandler(function ($text) {
          return preg_replace('/\n{3,}/', "\n\n", $text); // Collapse excessive newlines
      });
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle