Search code examples
phpxmlxpathdomxpath

PHP DomXPath not selecting empty text nodes


I'm trying to select nodes which don't contain any text. This bit of php code skips the empty node in the sample xml. However, when I try an online tester (like http://freeformatter.com/xpath-tester.html) it doesn't have any problem.

Is this a PHP thing?

My php code:

    $path = "//RecipeSteps/RecipeStep[not(text())]";
    $stepsQuery = $this->xpath->query($path);
    $numResults = $stepsQuery->length;

My sample xml:

<?xml version="1.0" encoding="utf-8"?>
<Recipes>
    <RecipeSteps>
      <RecipeStep number="1">Dummy content</RecipeStep>
      <RecipeStep number="2">Dummy content</RecipeStep>
      <RecipeStep number="3">Dummy content</RecipeStep>
      <RecipeStep number="4">Dummy content</RecipeStep>
      <RecipeStep number="5">Dummy content</RecipeStep>
      <RecipeStep number="6"></RecipeStep>
      <RecipeStep number="7">Variations</RecipeStep>
      <RecipeStep number="8">Some variation content..</RecipeStep>
    </RecipeSteps>
</Recipes>

Solution

  • If you are looking for a XPATH solution, use //RecipeSteps/(RecipeStep[string-length() = 0]). e.g

    $path = "//RecipeSteps/(RecipeStep[string-length() = 0])";
    $stepsQuery = $this->xpath->query($path);
    $numResults = $stepsQuery->length;