Извлечение URL из XML Sitemap
Просим ChatGPT написать простые сервисы, которые могут пригодиться в работе и смотрим, что в итоге получится. Запросы пишем максимально простым и понятным языком.
Запрос первый:
Напиши, код сервиса, который позволяет получить список URL адресов из XML Sitemap. Для написания кода используй html и php. У пользователя должна быть возможность вставить ссылку на XML Sitemap в специальное поле, а ниже получить список URL адресов. Каждый URL адрес должен быть на отдельной строке. У блока надо предусмотреть кнопку для быстрого копирования всего списка. Для оформления используй минималистичный понятный интерфейс на основе bootstrap 5. Внизу страницы добавь текстовый блок, в котором укажи, что данный код сгенерирован ChatGPT, укажи версию и свои параметры, укажи время генерации.
Вы можете сразу перейти по ссылке и посмотреть результат.
Размышления системы:
Reasoned about XML Sitemap service code for 30 seconds
Okay, the task is to create a service that lists URL addresses from an XML Sitemap using HTML and PHP. The user should be able to paste the sitemap URL into a field and see the URLs listed below, each on a separate line. Also, there has to be a button to quickly copy the list. For the design, I'll use a minimalist interface with Bootstrap 5. At the bottom, I need to add info about ChatGPT, its version, and the generated time. I'll get to work on that! I’m designing a service where URL addresses from an XML Sitemap are listed, each on its own line. There needs to be a button for copying the entire list. The interface will be minimalistic and use Bootstrap 5. A text block at the bottom will indicate that the code was generated by ChatGPT, with version info and generation time. The code will be a mix of HTML and PHP. To get the URLs, PHP will fetch the sitemap, parse it, and extract each URL. I'll also include the generation time in the UI.
Okay, the task is to create a service that lists URL addresses from an XML Sitemap using HTML and PHP. The user should be able to paste the sitemap URL into a field and see the URLs listed below, each on a separate line. Also, there has to be a button to quickly copy the list. For the design, I'll use a minimalist interface with Bootstrap 5. At the bottom, I need to add info about ChatGPT, its version, and the generated time. I'll get to work on that! I’m designing a service where URL addresses from an XML Sitemap are listed, each on its own line. There needs to be a button for copying the entire list. The interface will be minimalistic and use Bootstrap 5. A text block at the bottom will indicate that the code was generated by ChatGPT, with version info and generation time. The code will be a mix of HTML and PHP. To get the URLs, PHP will fetch the sitemap, parse it, and extract each URL. I'll also include the generation time in the UI.
Ниже приведён пример кода, который реализует описанный функционал в одном файле (например, index.php):
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Извлечение URL из XML Sitemap</title>
<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container my-5">
<h1 class="mb-4">Извлечение URL из XML Sitemap</h1>
<!-- Форма для ввода URL XML Sitemap -->
<form method="post">
<div class="mb-3">
<label for="sitemapUrl" class="form-label">Ссылка на XML Sitemap:</label>
<input type="url" name="sitemap_url" class="form-control" id="sitemapUrl" placeholder="https://example.com/sitemap.xml" required>
</div>
<button type="submit" class="btn btn-primary">Получить URL</button>
</form>
<hr>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['sitemap_url'])) {
$sitemapUrl = filter_var($_POST['sitemap_url'], FILTER_SANITIZE_URL);
// Получаем содержимое XML Sitemap
$xmlContent = @file_get_contents($sitemapUrl);
if ($xmlContent === false) {
echo '<div class="alert alert-danger mt-3">Не удалось получить XML по указанной ссылке.</div>';
} else {
libxml_use_internal_errors(true);
$xml = simplexml_load_string($xmlContent);
if ($xml === false) {
echo '<div class="alert alert-danger mt-3">Не удалось разобрать XML. Проверьте корректность файла.</div>';
} else {
// Ищем все теги <loc> внутри элементов <url>
$urls = $xml->xpath('//url/loc');
if ($urls === false || empty($urls)) {
echo '<div class="alert alert-warning mt-3">URL адреса не найдены в XML Sitemap.</div>';
} else {
echo '<div class="mb-3">';
echo '<label class="form-label">Список URL:</label>';
echo '<textarea class="form-control" id="urlList" rows="10" readonly>';
foreach ($urls as $url) {
echo trim((string)$url) . "\n";
}
echo '</textarea>';
echo '</div>';
echo '<button class="btn btn-secondary" onclick="copyToClipboard()">Скопировать список</button>';
}
}
}
}
?>
<!-- jаvascript для копирования списка URL -->
<script>
function copyToClipboard() {
var copyText = document.getElementById("urlList");
copyText.select();
copyText.setSelectionRange(0, 99999); // Для мобильных устройств
document.execCommand("copy");
alert("Список скопирован в буфер обмена!");
}
</script>
<hr>
<!-- Информационный блок о генерации кода -->
<footer class="mt-4">
<p class="text-muted" style="font-size: 0.9em;">
Данный код сгенерирован ChatGPT, версия GPT-4, параметры: «ChatGPT API». Время генерации: <?php echo date('Y-m-d H:i:s'); ?>.
</p>
</footer>
</div>
<!-- Bootstrap 5 JS Bundle -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Пояснения:
- HTML и Bootstrap 5: Используется подключение Bootstrap 5 через CDN для создания минималистичного интерфейса.
- PHP-обработка: При отправке формы скрипт получает XML-содержимое по указанному URL, парсит его с помощью simplexml_load_string и ищет все элементы <loc>.
- Вывод URL: Все найденные URL выводятся в <textarea> — каждый URL на новой строке.
- Кнопка копирования: При нажатии кнопки вызывается jаvascript-функция copyToClipboard(), которая копирует содержимое текстового поля в буфер обмена.
- Информационный блок: Внизу страницы выводится блок с информацией о том, что код сгенерирован ChatGPT, указывается версия.
Этот пример можно сохранить как один файл и разместить на сервере с поддержкой PHP.
Вы можете сразу перейти по ссылке и посмотреть результат.