Ajay Ajay - 5 months ago 22
PHP Question

PHP + XPath get nodes value in between Specified Dates

My XML file looks like :

<record>
<name>John</name>
<StartDate>01-05-2016</StartDate>
<EndDate>30-10-2016</EndDate>
</record>
<record>
<name>Jerry</name>
<StartDate>29-04-2016</StartDate>
<EndDate>30-06-2016</EndDate>
</record>
<record>
<name>Mike</name>
<StartDate>05-06-2016</StartDate>
<EndDate>25-08-2016</EndDate>
</record>


I have Two Dates Say :

start date: 30-04-2016 and,
end date: 27-08-2016


I want to write a Xpath Query which will return all the record which have
<StartDate>
and
<EndDate>
In between the above two dates(Both Inclusive).

Answer

You can parse data and add to an array, as a stdClass or whatever you like most:

<?php

$xml =
    '<root>
        <record>
            <name>John</name>
            <StartDate>01-05-2016</StartDate>
            <EndDate>30-10-2016</EndDate>
        </record>
        <record>
            <name>Jerry</name>
            <StartDate>29-04-2016</StartDate>
            <EndDate>30-06-2016</EndDate>
        </record>
        <record>
            <name>Mike</name>
            <StartDate>05-06-2016</StartDate>
            <EndDate>25-08-2016</EndDate>
        </record>
    </root>';

$doc= new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXpath($doc);
$elements = $xpath->query("//record");

$output = [];

$format = 'd-m-Y';
$startDate = DateTime::createFromFormat($format, '30-04-2016');
$endDate = DateTime::createFromFormat($format, '27-08-2016');

foreach($elements as $element) {
    $elementStartDate = DateTime::createFromFormat($format, $element->getElementsByTagName("StartDate")->item(0)->nodeValue);
    $elementEndDate = DateTime::createFromFormat($format, $element->getElementsByTagName("EndDate")->item(0)->nodeValue);

    if( ($startDate <= $elementStartDate) &&
        ($endDate >= $elementEndDate)) {
        $obj = new stdClass;
        $obj->name = $element->getElementsByTagName("name")->item(0)->nodeValue;
        $obj->startDate = $element->getElementsByTagName("StartDate")->item(0)->nodeValue;
        $obj->endDate = $element->getElementsByTagName("EndDate")->item(0)->nodeValue;
        $output[] = $obj;
    }
}

var_dump($output);

Output

array(1) {
  [0]=>
  object(stdClass)#10 (3) {
    ["name"]=>
    string(4) "Mike"
    ["startDate"]=>
    string(10) "05-06-2016"
    ["endDate"]=>
    string(10) "25-08-2016"
  }
}