【发布时间】:2012-06-30 16:35:54
【问题描述】:
我在寻找某些类/元素的页面上运行 php 脚本,如果类/元素不存在,我有时可能会收到 “尝试获取非对象的属性” 错误.
我想知道如何处理此错误,以便我可以将自己的 null 值分配给变量,因为使用 if 语句或 is_null 似乎不起作用。
查看下面的代码以更好地理解我的意思。
在if($size = $elem->find('.size',0)->plaintext) 行上,'history' 元素将抛出错误,因为类大小不存在。
函数:getInfo
function getInfo($link){
$page = file_get_html($link);
if($page){
$categoryLink = array();
$categoryName = array();
$categorySize = array();
if($container = $page->find('.infoContainer',1)){
foreach($container->find('.element') as $elem){
if($link = $elem->find('a',0)->href){
$categoryLink[] = $link;
}else{
$categoryLink[] = "";
}
if($name = $elem->find('.name',0)->plaintext){
$categoryName[] = $name;
}else{
$categoryName[] = "";
}
if($size = $elem->find('.size',0)->plaintext){
$categorySize[] = $size;
}else{
$categorySize[] = 0;
}
}
}
}
}
www.example.com
<div class='infoContainer'>
<div class='element'>
<a href='www.example.com/physics'>
<div class='name'>physics</div>
<div class='size'>1000</div>
</div>
<div class='element'>
<a href='www.example.com/math'>
<div class='name'>math</div>
<div class='size'>800</div>
</div>
<div class='element'>
<a href='www.example.com/history'>
<div class='name'>history</div>
</div>
</div>
调用函数
getInfo("www.example.com");
【问题讨论】:
标签: php dom web-crawler