2012-11-28 14 views
0

내 문서에 여러 유형의 <a>이 있습니다. 내가 선택하고 싶은 경우에만 아래의 마크 업 주어진 예를 들어 <a title="more data *">Selectind 특성 내용을 기반으로 한 DOM 요소

, 나는 제 1 및 제 2 <a>을 선택 좋아하지만, 건너 뛸 것 같은 그 title 속성 텍스트로 시작하는 <a> "더 많은 데이터를 ..." titlemore data으로 시작하지 않으므로 <a>에는 제목 속성조차 없기 때문에 세 번째는 건너 뜁니다.

<a title="more data some text" href="http://mypage.com/page.html">More</a> 
<a title="more data other text" href="http://mypage.com/page.html">More</a> 
<a title="not needed" href="http://mypage.com/page.html">Not needed</a> 
<a href="http://mypage.com/page.html">Not needed</a> 

DOMXPath를 사용하고 있습니다. 내 쿼리는 어떻게 생겼습니까? title 속성의 값이 지정된 문자열을 start with해야 이러한 predicate를 사용

//a[starts-with(@title, "more data ")] 

:

$xpath = new DOMXPath($doc); 
$q = $xpath->query('//a'); 

답변

1

당신은 같은 쿼리를 사용할 수 있습니다.


$doc = new DOMDocument; 
$doc->loadXML('<example> 
<a title="more data some text" href="http://mypage.com/page.html">More</a> 
<a title="more data other text" href="http://mypage.com/page.html">More</a> 
<a title="not needed" href="http://mypage.com/page.html">Not needed</a> 
<a href="http://mypage.com/page.html">Not needed</a> 
</example>'); 

$xpath = new DOMXPath($doc); 
$links = $xpath->query('//a[starts-with(@title, "more data ")]'); 

echo "Found {$links->length} links", PHP_EOL; 
foreach ($links as $link) { 
    echo $link->getAttribute('href'), PHP_EOL; 
} 

그리고 here's the above example running online.