Skip to content

Instantly share code, notes, and snippets.

@Golpha

Golpha/test.php Secret

Created December 13, 2014 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Golpha/bdd4a46647a2a4cb6504 to your computer and use it in GitHub Desktop.
Save Golpha/bdd4a46647a2a4cb6504 to your computer and use it in GitHub Desktop.
<?php
# create DOM instance
$dom = new DOMDocument();
$dom->load('test.xml');
# create XPATH instance of DOM
$xpath = new DOMXPath($dom);
# define xpath query to date value
$datePath = './bar/date';
# export all childs from root to array
$items = iterator_to_array($dom->documentElement->childNodes);
# filter out Text Nodes
$items = array_filter($items, function(DOMNode $current) {
return ! $current instanceof DOMText;
});
# sort items by date value
usort($items, function(DOMNode $a, DOMNode $b) use ($datePath, $xpath) {
$dateElements['a'] = $xpath->query($datePath, $a);
$dateElements['b'] = $xpath->query($datePath, $b);
$date['a'] = DateTime::createFromFormat('d.m.Y', trim($dateElements['a'][0]->nodeValue));
$date['b'] = DateTime::createFromFormat('d.m.Y', trim($dateElements['b'][0]->nodeValue));
if ( $date['a'] == $date['b'] ) {
return 0;
}
return $date['a'] < $date['b'] ? -1 : 1;
});
# apply running index to the sorted array
$ordered = array_values($items);
# define the search object
$searchFor = DateTime::createFromFormat('d.m.Y', '24.12.2014');
# search
$result = null;
foreach ( $ordered as $key => $element ) {
$current = DateTime::createFromFormat('d.m.Y', trim($element->nodeValue));
if ( $current < $searchFor || $current > $searchFor ) {
continue;
}
$result = compact('key', 'element');
}
if ( empty($result) ) {
echo 'nothing found.';
}
else if ( $result['key'] > 0 ) {
echo 'previous date of '.$searchFor->format('d.m.Y').' is '.trim($ordered[ $result['key'] - 1 ]->nodeValue);
}
else {
echo 'search value was found, but has no previous date';
}
<?xml version="1.0" encoding="utf-8" ?>
<data>
<foo>
<bar>
<date>01.04.2014</date>
</bar>
</foo>
<foo>
<bar>
<date>03.09.2014</date>
</bar>
</foo>
<foo>
<bar>
<date>04.05.2014</date>
</bar>
</foo>
<foo>
<bar>
<date>13.02.2014</date>
</bar>
</foo>
<foo>
<bar>
<date>24.12.2014</date>
</bar>
</foo>
<foo>
<bar>
<date>19.03.2014</date>
</bar>
</foo>
<foo>
<bar>
<date>23.11.2014</date>
</bar>
</foo>
<foo>
<bar>
<date>01.08.2014</date>
</bar>
</foo>
</data>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment