2012-11-19 42 views
5

Đây là mã PHP của tôi:PHP SimpleXML xpath: chứa và vị trí

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

Và đây là file 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> 

Làm thế nào để tôi có được 2 yếu tố đầu tiên mà nó thẻ chứa ' thú vật' ?

Kết quả xpath phải là post:id=1post:id=3, nhưng được xem là trả lại tất cả các phần tử có chứa animal.

Trả lời

4

Đặt phần chính XPath trong () khung, tức là .:

(//post/misc[contains(tags,"animal")])[position() <= 2] 
Các vấn đề liên quan