PHP SimpleXML xpath:包含和位置

MPh*_*huc 5 xml xpath position contains

这是我的PHP代码:

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

这是XML文件:

<?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>
Run Code Online (Sandbox Code Playgroud)

如何获得标签中包含"动物"的2个第一个元素?

xpath结果应该是post:id=1post:id=3,但它可以返回包含的所有元素animal.

Kir*_*huk 4

将主要的 XPath 部分放在()括号中,即:

(//post/misc[contains(tags,"animal")])[position() <= 2]
Run Code Online (Sandbox Code Playgroud)