Skip to content

Troubleshooting

Rumen Damyanov edited this page Sep 22, 2025 · 1 revision

Troubleshooting

Common issues, solutions, and debugging strategies when working with the PHP-SEO package.

Common Issues

Installation Problems

Composer Installation Fails

Problem: Composer cannot install the package or dependencies fail to resolve.

Solutions:

# Clear Composer cache
composer clear-cache

# Update Composer
composer self-update

# Install with verbose output
composer install -vvv

# Force requirements update
composer update --with-dependencies

PHP Version Compatibility

Problem: Package requires newer PHP version than available.

Error: requires php ^8.1.0 but your php version (8.0.x) does not satisfy that requirement

Solutions:

  • Upgrade PHP to version 8.1 or higher
  • Use Docker with appropriate PHP version
  • Check hosting provider's PHP version options
# Check current PHP version
php -v

# Update PHP (Ubuntu/Debian)
sudo apt update
sudo apt install php8.1

# Update PHP (macOS with Homebrew)
brew install php@8.1

Configuration Issues

Invalid Configuration Values

Problem: Configuration not being applied or causing errors.

Debugging:

use Rumenx\PhpSeo\Config\SeoConfig;

// Enable debug mode
$config = new SeoConfig([
    'debug' => true,
    'log_level' => 'debug'
]);

// Validate configuration
$seo = new SeoManager($config);
$configData = $seo->getConfig()->toArray();
var_dump($configData);

Missing Required Configuration

Problem: Required configuration keys are missing.

Error: Configuration key 'default_title' is required

Solution:

$config = new SeoConfig([
    'default_title' => 'Your Site Name',
    'default_description' => 'Your site description',
    'base_url' => 'https://yoursite.com'
]);

Content Analysis Issues

HTML Parsing Errors

Problem: Content cannot be parsed or produces unexpected results.

Common Causes:

  • Malformed HTML
  • Special characters not properly encoded
  • Very large HTML documents

Solutions:

// Enable error reporting
libxml_use_internal_errors(true);

$seo = new SeoManager();
$analysis = $seo->analyze($content);

// Check for parsing errors
$errors = libxml_get_errors();
foreach ($errors as $error) {
    echo "HTML Parse Error: " . $error->message;
}

Empty or Null Content

Problem: Analysis returns empty results.

Debugging:

$content = '<html><head><title>Test</title></head><body><h1>Hello</h1></body></html>';

if (empty($content)) {
    throw new InvalidArgumentException('Content cannot be empty');
}

$analysis = $seo->analyze($content);

// Debug output
echo "Title: " . ($analysis->getTitle() ?: 'No title found') . "\n";
echo "Headings: " . json_encode($analysis->getHeadings()) . "\n";

Character Encoding Issues

Problem: Special characters not displaying correctly.

Solution:

// Ensure proper encoding
$content = mb_convert_encoding($content, 'UTF-8', 'auto');

// Or specify encoding in configuration
$config = new SeoConfig([
    'encoding' => 'UTF-8',
    'html_parser' => [
        'encoding' => 'UTF-8'
    ]
]);

Meta Tags Generation

Meta Tags Not Appearing

Problem: Generated meta tags are empty or not included.

Debugging:

$analysis = $seo->analyze($content, [
    'title' => 'Test Title',
    'description' => 'Test Description'
]);

$metaTags = $analysis->getMetaTags();

if (empty($metaTags)) {
    // Check if analysis succeeded
    var_dump($analysis->toArray());
    
    // Check configuration
    var_dump($seo->getConfig()->get('meta_tags'));
}

Duplicate Meta Tags

Problem: Multiple identical meta tags generated.

Solution:

$config = new SeoConfig([
    'meta_tags' => [
        'remove_duplicates' => true,
        'override_existing' => true
    ]
]);

HTML Entity Encoding Issues

Problem: Special characters not properly escaped in meta tags.

Solution:

// Ensure proper escaping
$options = [
    'title' => htmlspecialchars('Title with "quotes" & symbols', ENT_QUOTES, 'UTF-8'),
    'description' => htmlspecialchars('Description with special chars', ENT_QUOTES, 'UTF-8')
];

Structured Data Problems

Invalid JSON-LD

Problem: Generated structured data is not valid JSON.

Debugging:

$structuredData = $analysis->generateStructuredData();
$decoded = json_decode($structuredData, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON Error: " . json_last_error_msg();
    echo "Raw data: " . $structuredData;
}

Missing Required Schema Properties

Problem: Schema validation fails due to missing required properties.

Solution:

// For Article schema
$options = [
    'type' => 'article',
    'title' => 'Required title',
    'author' => 'Required author name',
    'published_at' => '2024-01-01T10:00:00Z', // Required
    'image' => 'https://example.com/image.jpg' // Required for Article
];

Schema Type Not Supported

Problem: Trying to use unsupported schema type.

Error: Schema type 'CustomType' is not supported

Solution:

// Use custom schema builder
use Rumenx\PhpSeo\StructuredData\SchemaBuilder;

$schema = new SchemaBuilder();
$customSchema = $schema
    ->setType('CustomType')
    ->setProperty('name', 'Custom Value')
    ->build();

Performance Issues

Slow Analysis

Problem: SEO analysis takes too long to complete.

Solutions:

// Enable caching
$config = new SeoConfig([
    'performance' => [
        'cache_enabled' => true,
        'cache_ttl' => 3600
    ]
]);

// Limit content analysis
$config = new SeoConfig([
    'content_analysis' => [
        'max_content_length' => 50000,
        'skip_large_blocks' => true
    ]
]);

// Enable lazy loading
$config = new SeoConfig([
    'performance' => [
        'lazy_loading' => true
    ]
]);

High Memory Usage

Problem: Analysis consumes too much memory.

Solutions:

// Set memory limits
ini_set('memory_limit', '256M');

// Use streaming for large content
if (strlen($content) > 1000000) {
    $content = substr($content, 0, 1000000);
}

// Enable garbage collection
gc_enable();
gc_collect_cycles();

Framework Integration Issues

Laravel Integration Problems

Problem: Service provider not loading or Blade directives not working.

Solutions:

# Clear Laravel caches
php artisan cache:clear
php artisan config:clear
php artisan view:clear

# Publish configuration
php artisan vendor:publish --provider="Rumenx\PhpSeo\Laravel\SeoServiceProvider"

Symfony Integration Problems

Problem: Services not autowired or Twig extensions not working.

Solutions:

# Clear Symfony cache
php bin/console cache:clear

# Debug container
php bin/console debug:container SeoManager

Check service configuration:

# config/services.yaml
services:
    Rumenx\PhpSeo\SeoManager:
        autowire: true
        public: true

Debugging Strategies

Enable Debug Mode

$config = new SeoConfig([
    'debug' => true,
    'log_level' => 'debug',
    'verbose_errors' => true
]);

$seo = new SeoManager($config);

Logging and Monitoring

use Psr\Log\LoggerInterface;

class DebugSeoManager extends SeoManager
{
    private LoggerInterface $logger;

    public function __construct(SeoConfig $config, LoggerInterface $logger)
    {
        parent::__construct($config);
        $this->logger = $logger;
    }

    public function analyze(string $content, array $options = []): SeoAnalysis
    {
        $this->logger->info('Starting SEO analysis', [
            'content_length' => strlen($content),
            'options' => $options
        ]);

        try {
            $analysis = parent::analyze($content, $options);
            
            $this->logger->info('SEO analysis completed', [
                'title' => $analysis->getTitle(),
                'headings_count' => count($analysis->getHeadings())
            ]);

            return $analysis;
        } catch (Exception $e) {
            $this->logger->error('SEO analysis failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }
}

Step-by-Step Debugging

function debugSeoAnalysis(string $content, array $options = []): void
{
    echo "=== SEO Analysis Debug ===\n";
    
    // 1. Check content
    echo "Content length: " . strlen($content) . "\n";
    echo "Content preview: " . substr(strip_tags($content), 0, 100) . "...\n\n";
    
    // 2. Check configuration
    $config = new SeoConfig();
    echo "Configuration: " . json_encode($config->toArray(), JSON_PRETTY_PRINT) . "\n\n";
    
    // 3. Perform analysis
    $seo = new SeoManager($config);
    
    try {
        $analysis = $seo->analyze($content, $options);
        
        // 4. Check results
        echo "Title: " . ($analysis->getTitle() ?: 'None') . "\n";
        echo "Description: " . ($analysis->getDescription() ?: 'None') . "\n";
        echo "Headings: " . json_encode($analysis->getHeadings()) . "\n";
        echo "Meta tags length: " . strlen($analysis->getMetaTags()) . "\n";
        
        // 5. Check structured data
        $structuredData = $analysis->generateStructuredData();
        echo "Structured data: " . (!empty($structuredData) ? 'Generated' : 'None') . "\n";
        
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
        echo "Trace: " . $e->getTraceAsString() . "\n";
    }
}

Memory and Performance Debugging

function profileSeoAnalysis(string $content): array
{
    $startTime = microtime(true);
    $startMemory = memory_get_usage();

    $seo = new SeoManager();
    $analysis = $seo->analyze($content);

    $endTime = microtime(true);
    $endMemory = memory_get_usage();

    return [
        'execution_time' => $endTime - $startTime,
        'memory_used' => $endMemory - $startMemory,
        'peak_memory' => memory_get_peak_usage(),
        'analysis_completed' => $analysis instanceof SeoAnalysis
    ];
}

Error Messages Reference

Common Error Messages and Solutions

"Configuration key 'X' is required"

  • Cause: Missing required configuration
  • Solution: Add the required configuration key

"Content cannot be empty or null"

  • Cause: Empty content passed to analyze()
  • Solution: Ensure content is not empty before analysis

"Invalid HTML structure detected"

  • Cause: Malformed HTML content
  • Solution: Validate and fix HTML structure

"Schema type 'X' is not supported"

  • Cause: Using unsupported schema type
  • Solution: Use supported schema type or create custom schema

"Memory limit exceeded"

  • Cause: Content too large for available memory
  • Solution: Increase memory limit or reduce content size

"JSON encoding failed"

  • Cause: Invalid data for JSON encoding
  • Solution: Check data for circular references or invalid UTF-8

Testing and Validation

Validate Installation

// Basic installation test
try {
    $seo = new SeoManager();
    $analysis = $seo->analyze('<html><title>Test</title></html>');
    echo "Installation successful: " . $analysis->getTitle();
} catch (Exception $e) {
    echo "Installation error: " . $e->getMessage();
}

Validate Configuration

// Configuration validation
$config = new SeoConfig([
    'default_title' => 'Test',
    'default_description' => 'Test description'
]);

$validator = new ConfigValidator();
$errors = $validator->validate($config);

if (!empty($errors)) {
    foreach ($errors as $error) {
        echo "Config error: " . $error . "\n";
    }
}

Test with Sample Content

$sampleContent = '
<!DOCTYPE html>
<html>
<head>
    <title>Sample Page</title>
    <meta name="description" content="Sample description">
</head>
<body>
    <h1>Main Heading</h1>
    <p>Sample content for testing.</p>
</body>
</html>
';

$seo = new SeoManager();
$analysis = $seo->analyze($sampleContent);

// Validate results
assert($analysis->getTitle() === 'Sample Page');
assert(!empty($analysis->getMetaTags()));
assert(count($analysis->getHeadings()['h1']) === 1);

echo "All tests passed!\n";

Getting Help

Community Resources

  1. GitHub Issues: Report bugs or request features
  2. Documentation: Check the complete documentation
  3. Examples: Review example implementations
  4. Stack Overflow: Search for similar issues

Reporting Issues

When reporting issues, include:

  1. PHP Version: php -v
  2. Package Version: Check composer.json
  3. Error Message: Complete error message and stack trace
  4. Sample Code: Minimal code that reproduces the issue
  5. Expected vs Actual: What you expected vs what happened

Debug Information Collection

function collectDebugInfo(): array
{
    return [
        'php_version' => PHP_VERSION,
        'extensions' => get_loaded_extensions(),
        'memory_limit' => ini_get('memory_limit'),
        'max_execution_time' => ini_get('max_execution_time'),
        'package_version' => '1.0.0', // Your package version
        'os' => PHP_OS,
        'sapi' => PHP_SAPI
    ];
}

This troubleshooting guide should help you resolve most common issues with the PHP-SEO package. For specific problems not covered here, please check the GitHub issues or create a new issue with detailed information.

Clone this wiki locally