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

Fdomdocument Laravel Package

theseer/fdomdocument

Archived PHP library extending DOMDocument to throw exceptions instead of warnings/notices, plus handy shortcuts like XPath query helpers and appendElement variants. Drop-in replacement for DOM with libxml support; works with PHP 5.3.3–8.1 (v1.6.7).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:
    composer require theseer/fdomdocument:^1.6
    
  2. Replace DOMDocument with fDOMDocument:
    use TheSeer\fDOM\fDOMDocument;
    
    $dom = new fDOMDocument();
    $dom->loadXML('<root><child/></root>');
    
  3. Handle Exceptions:
    try {
        $dom->loadXML('<invalid>xml</invalid>');
    } catch (fDOMException $e) {
        // Log or handle error (no PHP warnings)
        Log::error($e->getMessage());
    }
    

First Use Case: Safe XML Parsing

$dom = new fDOMDocument();
try {
    $dom->loadXML($xmlString);
    $nodes = $dom->query('//book'); // XPath query
    foreach ($nodes as $node) {
        echo $node->nodeValue;
    }
} catch (fDOMException $e) {
    // Structured error handling
    abort(500, 'XML parsing failed: ' . $e->getMessage());
}

Key Starting Points

  • Documentation: README.md (focus on Usage Samples).
  • API Reference: Methods mirror DOMDocument but add shortcuts like queryOne(), select() (CSS), and appendElement().
  • Laravel Integration: Use in service classes (e.g., XmlParserService) or Blade components for dynamic XML/HTML generation.

Implementation Patterns

Core Workflows

1. Error-Free DOM Manipulation

  • Pattern: Wrap all DOM operations in try-catch blocks to avoid PHP warnings.
  • Example:
    try {
        $dom->loadHTML($html);
        $title = $dom->queryOne('//title')->nodeValue;
    } catch (fDOMException $e) {
        $title = 'Default Title';
    }
    

2. CSS Selector Queries

  • Pattern: Use select() for jQuery-like syntax (faster than XPath for simple queries).
  • Example:
    $links = $dom->select('a[href^="https://"]');
    foreach ($links as $link) {
        $link->setAttribute('target', '_blank');
    }
    

3. Dynamic Node Creation

  • Pattern: Use appendElement() shortcuts to reduce boilerplate.
  • Example:
    $root = $dom->appendElement('catalog');
    $root->appendElement('product', null, null, 'name="Laptop"');
    

4. XPath Prepared Statements

  • Pattern: Reuse XPath queries with fDOMXPath.
  • Example:
    $xpath = $dom->createXPath();
    $query = $xpath->prepare('//item[@id=:id]');
    $query->bindValue('id', 123);
    $item = $query->queryOne();
    

5. HTML/XML Generation

  • Pattern: Leverage __toString() for quick output.
  • Example:
    $dom = new fDOMDocument();
    $dom->appendElement('response')->appendTextNode('Success');
    return response($dom->saveHTML(), 200);
    

Laravel-Specific Patterns

Service Layer Integration

  • Encapsulate DOM logic in a service class:
    class XmlParserService {
        public function parse(string $xml): array {
            $dom = new fDOMDocument();
            try {
                $dom->loadXML($xml);
                return $this->extractData($dom);
            } catch (fDOMException $e) {
                Log::error($e->getMessage());
                return [];
            }
        }
    }
    

Blade Directives for Dynamic XML

  • Create a Blade directive to generate XML snippets:
    Blade::directive('xml', function ($expression) {
        $dom = new fDOMDocument();
        eval("\$dom->$expression");
        return "<?php echo \$dom->saveXML(); ?>";
    });
    
    Usage:
    @xml('appendElement("user")->appendElement("name", null, null, "John")')
    

Form Request Validation with XML

  • Validate XML payloads in FormRequest:
    public function rules() {
        return [
            'xml_data' => ['required', function ($attribute, $value, $fail) {
                $dom = new fDOMDocument();
                try {
                    $dom->loadXML($value);
                } catch (fDOMException $e) {
                    $fail('Invalid XML: ' . $e->getMessage());
                }
            }],
        ];
    }
    

API Response Wrapping

  • Standardize API responses with XML:
    $response = new fDOMDocument();
    $response->appendElement('data')->appendTextNode($data);
    return response($response->saveXML(), 200, ['Content-Type' => 'application/xml']);
    

Gotchas and Tips

Pitfalls

1. Archived Package Risks

  • Issue: No updates for PHP 8.2+ or Laravel 10+.
  • Workaround: Test thoroughly with your PHP version. Monitor for DOM behavior changes in newer PHP releases.
  • Mitigation: Document the risk in your architecture decisions.

2. Exception Overhead

  • Issue: Exceptions may slow down high-frequency DOM operations (e.g., parsing thousands of XML files).
  • Workaround: Use fDOMException::setFullMessage(false) to reduce exception payload size:
    fDOMException::setFullMessage(false); // Disable full error details
    

3. CSS Selector Limitations

  • Issue: select() uses a subset of CSS selectors (not full jQuery syntax).
  • Workaround: Stick to XPath for complex queries or use a dedicated library like Symfony/CSSSelector.

4. PHP 8.1 Strict Typing

  • Issue: Some methods may throw type errors in PHP 8.1 (e.g., passing null where int is expected).
  • Workaround: Update to 1.6.7 (includes fixes for PHP 8.1).

5. Namespace Conflicts

  • Issue: fDOMDocument extends DOMDocument, but some IDEs may not recognize the extended methods.
  • Workaround: Use @method PHPDoc annotations or configure your IDE to recognize the package’s classes.

6. Cloning Issues

  • Issue: Cloning fDOMDocument may break XPath queries (fixed in 1.3.2+).
  • Workaround: Avoid cloning or ensure you’re on >=1.3.2.

7. LibXML Entities

  • Issue: Malformed entities (e.g., &amp;) may still trigger warnings despite exceptions.
  • Workaround: Pre-sanitize input or use libxml_use_internal_errors(true) before loading:
    libxml_use_internal_errors(true);
    $dom->loadHTML($html);
    libxml_clear_errors();
    

Debugging Tips

Enable Full Exception Messages

fDOMException::setFullMessage(true); // For detailed error debugging

Log DOM Errors

try {
    $dom->loadXML($xml);
} catch (fDOMException $e) {
    Log::debug('DOM Error', ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
}

Validate XML/HTML Before Parsing

if (!filter_var($xml, FILTER_VALIDATE_BOOLEAN, FILTER_FLAG_NO_ENCODED_SPACES)) {
    throw new \InvalidArgumentException('Invalid XML/HTML');
}

Performance Tips

Reuse XPath Objects

$xpath = $dom->createXPath(); // Reuse for multiple queries
$nodes = $xpath->query('//item');

Avoid Redundant Queries

// Bad: Query twice
$dom->query('//title');
$dom->query('//title');

// Good: Cache results
$titles = $dom->query('//title');

Use queryOne() for Single Nodes

$title = $dom->queryOne('//title'); // Faster than query() + first()

Extension Points

Custom Exception Handler

fDOMException::setExceptionHandler(function (fDOMException $e) {
    report($e); // Laravel's error reporting
    abort(500, 'DOM Error: ' . $e->getMessage());
});
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky