You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

需求:通过PHP循环生成XML文件,支撑FAQ实时搜索自动更新

Solution for Dynamically Generating FAQ Search XML via PHP

Got it, let's build this PHP script that automatically scans your scattered FAQ TXT files and generates an updated XML document—no code changes needed every time your FAQs get updated. Here's a complete, customizable solution:

Core Approach

  • Use configurable variables to define your FAQ directory and XML output path (so you never touch the core logic)
  • Recursively scan all subdirectories to find every TXT file
  • Parse each TXT into a structured FAQ entry (adjustable to your TXT format)
  • Generate a clean, valid XML file that your real-time search system can consume

Complete PHP Script

<?php
// --------------------------
// Configuration - Edit These!
// --------------------------
$faqRootDir = './faq_content'; // Path to your root directory with FAQ TXTs
$outputXmlFile = './faq_search_suggestions.xml'; // Where to save the generated XML
$txtFileEncoding = 'UTF-8'; // Match your TXT files' encoding (e.g., ISO-8859-1 if needed)

// Initialize XML document
$xmlDoc = new DOMDocument('1.0', 'UTF-8');
$xmlDoc->formatOutput = true; // Makes XML human-readable

// Create root node
$rootNode = $xmlDoc->createElement('faqSuggestions');
$xmlDoc->appendChild($rootNode);

// Recursive function to scan directories and process TXT files
function processFaqFiles($dir, $xml, $root, $encoding) {
    $directoryItems = scandir($dir);
    
    foreach ($directoryItems as $item) {
        // Skip parent/self directory markers
        if ($item === '.' || $item === '..') continue;
        
        $fullPath = $dir . DIRECTORY_SEPARATOR . $item;
        
        if (is_dir($fullPath)) {
            // Dig into subdirectories
            processFaqFiles($fullPath, $xml, $root, $encoding);
        } elseif (pathinfo($fullPath, PATHINFO_EXTENSION) === 'txt') {
            // Read and process the TXT file
            $fileContent = file_get_contents($fullPath);
            if (!$fileContent) {
                error_log("Could not read FAQ file: $fullPath");
                continue;
            }
            
            // Convert content to UTF-8 for consistent XML encoding
            $fileContent = mb_convert_encoding($fileContent, 'UTF-8', $encoding);
            
            // --------------------------
            // Customize TXT Parsing Here!
            // --------------------------
            // This assumes each TXT has:
            // - Line 1: FAQ question
            // - Lines 2+: FAQ answer
            // Adjust this logic if your TXT uses a different format (e.g., delimiters)
            $contentLines = explode("\n", trim($fileContent));
            $faqQuestion = isset($contentLines[0]) ? trim($contentLines[0]) : 'Unlabeled FAQ';
            $faqAnswer = implode("\n", array_slice($contentLines, 1));
            
            // Build XML nodes for the FAQ entry
            $faqEntry = $xml->createElement('faqItem');
            
            // Add question node
            $questionNode = $xml->createElement('question');
            $questionNode->appendChild($xml->createTextNode($faqQuestion));
            $faqEntry->appendChild($questionNode);
            
            // Add answer node
            $answerNode = $xml->createElement('answer');
            $answerNode->appendChild($xml->createTextNode($faqAnswer));
            $faqEntry->appendChild($answerNode);
            
            // Optional: Add source file path as an attribute (for debugging/maintenance)
            $faqEntry->setAttribute('sourceFile', $fullPath);
            
            // Attach the entry to the root node
            $root->appendChild($faqEntry);
        }
    }
}

// Run the file processing and XML generation
processFaqFiles($faqRootDir, $xmlDoc, $rootNode, $txtFileEncoding);

// Save the final XML file
if ($xmlDoc->save($outputXmlFile)) {
    echo "Success! XML file generated at: $outputXmlFile";
} else {
    echo "Error: Failed to write XML file. Check directory permissions.";
}
?>

Key Details to Note

  1. Configuration Flexibility: All editable settings are at the top—just update the directory paths and encoding without touching the rest of the code.
  2. Recursive Scanning: The script automatically checks all subdirectories under your root FAQ folder, so you can organize your TXTs however you want.
  3. Customizable TXT Parsing: The current logic assumes a simple line-based format, but you can modify the parsing section to match your actual TXT structure (e.g., using a --- delimiter between question and answer).
  4. Error Handling: Logs errors for unreadable files instead of crashing the whole script, so one bad file won't break your entire XML generation.
  5. Valid XML: Uses PHP's DOMDocument to ensure the output is well-formed and valid XML, which is critical for your real-time search system.

How to Use

  1. Upload this script to your web server (e.g., name it generate-faq-xml.php).
  2. Update the configuration variables to point to your FAQ directory and desired XML output path.
  3. Access the script via its URL (e.g., http://your-domain.com/generate-faq-xml.php)—this will trigger the XML generation.
  4. For automatic updates, set up a cron job (on Linux) or scheduled task (on Windows) to run this script at regular intervals, or run it manually whenever you update your FAQ TXT files.

内容的提问来源于stack exchange,提问作者Samuel Chopard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:27:56