LoginSignup
2
0

More than 5 years have passed since last update.

SimpleXMLでsitemap.xmlを作成する時にモバイルのURLも載せる

Posted at

sitemap.xml をイチから作る機会があったので。

今回はスマホ向けのサイトが別URLだったので、alternateタグ(<link rel="alternate">)を入れるついでにサイトマップにも入れてみました。

サイトマップ内にアノテーションを含めることができるそうです。
https://developers.google.com/search/mobile-sites/mobile-seo/separate-urls?hl=ja

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <url>
    <loc>http://www.example.com/page-1/</loc>
    <xhtml:link
      rel="alternate"
      media="only screen and (max-width: 640px)"
      href="http://m.example.com/page-1" />
  </url>
</urlset>

そしてPHPでSimpleXMLを利用している場合に、以下を入れる方法です。

<xhtml:link rel="alternate" media="only screen and (max-width: 640px)" href="http://m.example.com/page-1" />

以下コード

<?php
$xmlData = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');

$urlTag = $xml_data->addChild('url');
$urlTag->addChild('loc', 'http://www.example.com/page-1/');
$alternate = $url->addChild('xhtml:link', NULL, 'http://www.w3.org/1999/xhtml');
$alternate->addAttribute('rel', 'alternate');
$alternate->addAttribute('media', 'only screen and (max-width: 640px)');
$alternate->addAttribute('href', 'http://m.example.com/page-1');
$xml_data->asXML(__DIR__ . '/sitemap.xml');

xhtml:link でnamespaceを入れないと linkとして追加されて思い通りにならないですよー、というお話でした。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0