Knowledge Base

Empty filter

Laravel console code

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;

class ImportBookmarks extends Command
{
// Define the command signature
protected $signature = 'import:bookmarks {file}';

// Define the command description
protected $description = 'Import bookmarks from an HTML file into the knowledge_base table';

public function handle()
{
$filePath = $this->argument('file');

if (!file_exists($filePath)) {
Log::error("File not found: $filePath");
$this->error("File not found: $filePath");
return;
}

$html = file_get_contents($filePath);
$dom = new \DOMDocument();
@$dom->loadHTML($html); // Suppress warnings due to malformed HTML

$xpath = new \DOMXPath($dom);
foreach ($dom->getElementsByTagName('h3') as $header) {
$title = trim($header->textContent);
$slug = Str::slug($title);
$content = '';

// Find the corresponding <DL> element
$dlElements = $xpath->query("following-sibling::dl[1]", $header->parentNode);

if ($dlElements->length > 0) {
Log::info("Found <DL> for header '$title'");

foreach ($dlElements->item(0)->getElementsByTagName('a') as $link) {
$href = trim($link->getAttribute('href'));
$linkText = trim($link->textContent);

if (!empty($href) && !empty($linkText)) {
// Ensure links are stored properly
$content .= "<a href=\"$href\">$linkText</a><br>";
Log::info("Added link: <a href=\"$href\">$linkText</a>");
} else {
Log::warning("Empty href or link text under header '$title'");
}
}
} else {
Log::warning("No <DL> found after header '$title'");
}

if (!empty($title) && !empty($slug)) {
$data = [
'title' => $title,
'slug' => $slug,
'description' => '',
'content' => $content, // Correctly storing multiple links
'tags' => json_encode([]),
'author_id' => 8,
];

try {
DB::table('knowledge_base')->insert($data);
Log::info("Inserted successfully: " . json_encode($data));
} catch (\Illuminate\Database\QueryException $e) {
Log::error("Database error: " . $e->getMessage());
}
}
}
}
}

Published
Back to Index