Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SimpleXML xpath: contains and position

Here is my PHP code:

$xml = new SimpleXMLElement('data.xml', null, true);
$q = $xml->xpath('post/misc[contains(tags,"animal")][position() <= 2]');

And here is the XML file:

<?xml version="1.0" encoding="UTF-8" ?>
<posts>
    <post>
        <id>1</id>
        <misc>
            <tags>animal,tiger</tags>
            <prio>0.5</prio>
        </misc>
    </post>
    <post>
        <id>2</id>
        <misc>
            <tags>plant,coconut</tags>
            <prio>0.5</prio>
        </misc>
    </post>
    <post>
        <id>3</id>
        <misc>
            <tags>animal,lion</tags>
            <prio>0.5</prio>
        </misc>
    </post>
    <post>
        <id>4</id>
        <misc>
            <tags>animal,monkey</tags>
            <prio>0.5</prio>
        </misc>
    </post>
</posts>

How do I get the 2 first elements where it's tags contains 'animal' ?

The xpath result should be post:id=1 and post:id=3, but it's seen to return all elements which contains animal.

like image 819
MPhuc Avatar asked Oct 05 '22 22:10

MPhuc


1 Answers

Put main XPath part in () brackets, i.e.:

(//post/misc[contains(tags,"animal")])[position() <= 2]
like image 76
Kirill Polishchuk Avatar answered Oct 18 '22 15:10

Kirill Polishchuk