我试图从属性id中获取id,代码如下:
<?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-before(substring-after(//p[contains(text(),'Property ID:')][1], 'Property ID:'), '–'))");*/
$id = $xpath->evaluate('//div[contains(@class,"property-table")]')->item(0)->nodeValue;
preg_match("/Property ID :(.*)/", $id, $matches);
echo $matches[1];
但它不起作用;
Notice: Undefined offset: 1 in W:'Xampp'htdocs'X'index.php on line 12
怎么了?如果我制造像这样的刺痛
$id ="Property Details Property Type : Apartment Price $ 350 pm Building Size 72 Sqms Property ID : 1001192296";
并在我的代码中替换它。那么,myselt创建的数据和xpath中的grab创建的数据之间有什么区别呢?提前感谢您对我的帮助。
您的preg_match()
不工作,因为您从xpath获得的nodeValue
正是这样的:
Property Details
Property Type :
Apartment
Price
$ 350 pm
Building Size
72 Sqms
Property ID
:
1001192296
所以你必须这样尝试:
$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-before(substring-after(//p[contains(text(),'Property ID:')][1], 'Property ID:'), '–'))");*/
$id = $xpath->evaluate('//div[contains(@class,"property-table")]')->item(0)->nodeValue;
$id = preg_replace('!'s+!', ' ', $id);
preg_match("/Property ID :(.*)/", $id, $matches);
echo $matches[1];
这($id = preg_replace('!'s+!', ' ', $id);
)将把所有标签、单词之间的空白合并为一个空白。
更新:由于下面的注释,我现在获得了带有$xpath->evaluate()
的HTML的全文,并尝试匹配所有属性ID(比如只有数字和P数字)。
$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);
// this only returns the text of the whole page without html tags
$id = $xpath->evaluate( "//html" )->item(0)->nodeValue;
$id = preg_replace('!'s+!', ' ', $id);
// not a good regex, but matches the property IDs
preg_match_all("/Property ID( |):[ |](('w{0,1}[-]|)'d*)/", $id, $matches);
// after the changes you have to go for the matches is $matches[2]
foreach( $matches[2] as $property_id ) {
echo $property_id."<br>";
}
您需要检查preg_match()
是否真的找到了任何东西。
如果没有结果,就不会有$matches[1]
。您应该使用if(count($matches)>1) {... }
来解决您遇到的问题。