我遇到了问题,我想从其他网站获取数据并使用cURL在我的网站上显示。
例如,这是来自其他网站的数据,我想在我的网站上解析和显示。
<div class="users-name"> <a href='#'>User 1</a></div>
<div class="users-name"> <a href='#'>User 2</a></div>
<div class="users-name"> <a href='#'>User 3</a></div>
<div class="users-name"> <a href='#'>User 4</a></div>
<div class="users-name"> <a href='#'>User 5</a></div>
<div class="users-name"> <a href='#'>User 6</a></div>
<div class="users-name"> <a href='#'>User 7</a></div>
<div class="users-name"> <a href='#'>User 8</a></div>
<div class="users-name-address"><a href='#'>User 1 Address</a></div>
<div class="users-name-address"><a href='#'>User 2 Address</a></div>
<div class="users-name-address"><a href='#'>User 3 Address</a></div>
<div class="users-name-address"><a href='#'>User 4 Address</a></div>
<div class="users-name-address"><a href='#'>User 5 Address</a></div>
<div class="users-name-address"><a href='#'>User 6 Address</a></div>
<div class="users-name-address"><a href='#'>User 7 Address</a></div>
<div class="users-name-address"><a href='#'>User 8 Address</a></div>
目前我正在获取所有用户名,但现在我想获得所有这些地址以及用户名,因此我将使用正确的用户放置正确的地址。
到目前为止我已尝试过这个:
$curl = curl_init('www.domain.com/search.php');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$page = curl_exec($curl);
if(curl_errno($curl)) // check for execution errors
{
echo 'Scraper error: ' . curl_error($curl);
exit;
}
curl_close($curl);
$regex = '/<div class="users-name">(.*?)<\/div>/s';
if(preg_match_all($regex, $page, $list))
print_r($list[0]);
else
print "Not found";
答案 0 :(得分:0)
没有正则表达式的方法:
$dom = new DOMDocument();
@$dom->loadHTML($page);
$xpath = new DOMXPath($dom);
$queryName = '//div[@class = "users-name"]/a';
$queryAddress = '//div[@class = "users-name-address"]/a';
function getTextFromNodes($nodeList) {
$textArray = array();
foreach($nodeList as $listItem) {
$textArray[] = $listItem->textContent;
}
return $textArray;
}
$names = getTextFromNodes($xpath->query($queryName));
$addresses = getTextFromNodes($xpath->query($queryAddress));
$result = array_combine($names, $addresses);
print_r($result);