如何获取每个块中的链接 PHP DomReady?
How to get links in each block PHP DomReady?
我有以下 HTML DOM:
<div class="m">
<div class="cr"><a class="link" href="1">1</a><div class="title">1</div></div>
<div class="cr"><a class="link" href="2">2</a><div class="title">2</div></div>
<div class="cr"><a class="link" href="3">3</a><div class="title">3</div></div>
</div>
我需要在一个循环中获取值:链接的 .title
和 href
。
我试过了:
$similar = $xpath->query('//div[@class = "cr"]');
foreach ($similar as $key => $item) {
$href = ?
$title = ?
}
You could use the SimpleXMLElement
Class for that as demonstrated by the Snippet below which, you may Quick-Test Here.
<?php
$html = '<div class="m">
<div class="cr"><a href="1">1</a><div class="title">1st Node Value</div></div>
<div class="cr"><a href="2">2</a><div class="title">2nd Node Value</div></div>
<div class="cr"><a href="3">3</a><div class="title">3rd Node Value</div></div>
</div>';
$sXML = new SimpleXMLElement($html);
$links = $sXML->xpath("child::div/a");
$titles = $sXML->xpath("child::div/div");
$arrLinks = array();
$arrTitles = array();
foreach($links as $link){
$arrLinks[] = (string)$link->xpath("attribute::href")[0];
}
foreach($titles as $title){
$arrTitles[] = (string)$title;
}
var_dump($arrLinks);
// YIELDS::
array (size=3)
0 => string '1' (length=1)
1 => string '2' (length=1)
2 => string '3' (length=1)
var_dump($arrTitles);
// YIELDS::
array (size=3)
0 => string '1st Node Value' (length=14)
1 => string '2nd Node Value' (length=14)
2 => string '3rd Node Value' (length=14)
我有以下 HTML DOM:
<div class="m">
<div class="cr"><a class="link" href="1">1</a><div class="title">1</div></div>
<div class="cr"><a class="link" href="2">2</a><div class="title">2</div></div>
<div class="cr"><a class="link" href="3">3</a><div class="title">3</div></div>
</div>
我需要在一个循环中获取值:链接的 .title
和 href
。
我试过了:
$similar = $xpath->query('//div[@class = "cr"]');
foreach ($similar as $key => $item) {
$href = ?
$title = ?
}
You could use the
SimpleXMLElement
Class for that as demonstrated by the Snippet below which, you may Quick-Test Here.
<?php
$html = '<div class="m">
<div class="cr"><a href="1">1</a><div class="title">1st Node Value</div></div>
<div class="cr"><a href="2">2</a><div class="title">2nd Node Value</div></div>
<div class="cr"><a href="3">3</a><div class="title">3rd Node Value</div></div>
</div>';
$sXML = new SimpleXMLElement($html);
$links = $sXML->xpath("child::div/a");
$titles = $sXML->xpath("child::div/div");
$arrLinks = array();
$arrTitles = array();
foreach($links as $link){
$arrLinks[] = (string)$link->xpath("attribute::href")[0];
}
foreach($titles as $title){
$arrTitles[] = (string)$title;
}
var_dump($arrLinks);
// YIELDS::
array (size=3)
0 => string '1' (length=1)
1 => string '2' (length=1)
2 => string '3' (length=1)
var_dump($arrTitles);
// YIELDS::
array (size=3)
0 => string '1st Node Value' (length=14)
1 => string '2nd Node Value' (length=14)
2 => string '3rd Node Value' (length=14)