Skip to content

Instantly share code, notes, and snippets.

@spinsch
Last active January 24, 2019 16:02
Show Gist options
  • Save spinsch/242040b5ee49c71d2439a4fd073a22e7 to your computer and use it in GitHub Desktop.
Save spinsch/242040b5ee49c71d2439a4fd073a22e7 to your computer and use it in GitHub Desktop.
get last 20 elements from sitemap.xml with php
<?php
// this is for schema http://www.sitemaps.org/schemas/sitemap/0.9
// config
$lastNElements = 20;
// url or filepath
//$source = 'https://www.digitec.ch/sitemap0.xml';
$source = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
<url>
<loc>video post url/</loc>
<video:video>
<video:player_loc allow_embed="yes">yembed url/</video:player_loc>
<video:title>TITLE</video:title>
<video:description>DESCREPTIN</video:description>
<video:thumbnail_loc>IMAGE.jpg</video:thumbnail_loc>
<video:duration>384</video:duration>
</video:video>
</url>
</urlset>
XML;
// parsing
$xml = simplexml_load_string($source);
$xml->registerXPathNamespace('s', 'http://www.sitemaps.org/schemas/sitemap/0.9');
/**
* // = all nodes from current root
* s = defined namespace from below
* url = elements
* positon() = current node position
* last() = last node
*/
$xpath = '//s:url[position()>last()-'.$lastNElements.']';
foreach ($xml->xpath($xpath) as $element)
{
print_r((string)$element->loc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment