How to return only the result of the first match in XPath?

I tried using XPath string-afterto capture data after the Property ID: but the result is not the one I want. It displays the entire result mapped to the property identifier. I only want to P-000324. And here is my code

<?php
$getURL = file_get_contents('http://realestate.com.kh/residential-for-rent-in-phnom-penh-daun-penh-phsar-chas-2-beds-apartment-1001192296/');
$dom = new DOMDocument();
@$dom->loadHTML($getURL);
$xpath = new DOMXPath($dom);

echo $xpath->evaluate("normalize-space(substring-after(., 'Property ID:'))");

So how can I get him to get only one first result ?

+4
source share
1 answer

You can modify the XPath expression to select a row after only the first occurrence of the p containing Property ID:using the position index ( [1]).

, XPath , " :":

(//p[contains(text(),'Property ID:')])[1]

, , " :", P-000324:

echo $xpath->evaluate("normalize-space(substring-before(substring-after((//p[contains(text(),'Property ID:')])[1], 'Property ID:'), '–'))");

P-000324 .

. , , ​​. , " ", , , , XPath 1.0 ; XPath 2.0 .

+3

Source: https://habr.com/ru/post/1615450/


All Articles