Jump to content

String comparisons using xpath


Barand

Recommended Posts

I have some xml (which I hate and think is the biggest waste of space in the history of computing, but I guess we have to live with it) containing image elements and I am trying to find those images updated in the last week. ie lastUpdate > 2018-03-07.

 

Failing miserably I tried with the simpler type attributes with similar success.

 

The data

<?xml version="1.0" encoding="utf-8"?>
<result>
  <item id="5018">
    <texts>
      <text lastUpdate="2018-03-14T01:23:04+01:00" lang="en" />
    </texts>
    <images>
      <image type="a" lastUpdate="2018-01-05T09:26:21+01:00">
      </image>
      <image type="p" lastUpdate="2018-03-09T09:26:21+01:00">
      </image>
      <image type="r" lastUpdate="2018-03-09T09:26:21+01:00">
      </image>
    </images>
  </item>
</result>

The attempts:

$xml = simplexml_load_file('test.xml');
$x = $xml->xpath("//image[@type = 'a']");      // 1 result as expected
$x = $xml->xpath("//image[@type != 'a']");     // 2 results as expected  (types p and r)
$x = $xml->xpath("//image[@type > 'a']");      // 0 results ??????

$x = $xml->xpath("//image[@lastUpdate = '2018-03-09T09:26:21+01:00']");     // 2 results

// and the similar main problem:

$x = $xml->xpath("//image[@lastUpdate > '2018-03-07']");     // 0 results ??????

Any suggestions?

Link to comment
Share on other sites

This seems to work:

$x = $xml->xpath("//image[number(translate(substring-before(@lastUpdate, 'T'), '-', '')) > 20180307]");

The substring-before(@lastUpdate, 'T') returns the date string that comes before the 'T'.

 

Then, that value is used within translate([VALUE], '-', '') to remove the dashes in the date string.

 

Then, that value is used within number([VALUE]) to convert the resulting string 'YYYYMMDD' into a number value and is compared against the numeric value for your specified date.

 

You can compare on date and time if you use '+' in the substring-before() function and use '-T:' in the second parameter for the translate() function.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.