我正在尝试将标题,信息和时间整理到数组中。但是,我一直在获取数据。正如您在控制器中看到的那样,我使用getelementbyID来调用我的第一列表,但它向我显示了DOMElement对象。有人可以帮忙吗? :/
HTML:
<div class="col-sm-7 tracking">
<div class="box">
<ul id="first-list">
<li>
<span></span>
<div class="title">BKI</div>
<div class="info">SHIPMENT DELIVERED</div>
<div class="time">
<span>01/May/2020</span>
<span style="color:grey">9:05PM</span>
</div>
</li>
<li>
<span></span>
<div class="title">BKI</div>
<div class="info">SHIPMENT OUT FOR DELIVERY</div>
<div class="time">
<span>01/May/2020</span>
<span style="color:grey">8:56PM</span>
</div>
</li>
</ul>
</div>
Controller:
$DOM = new DOMDocument;
libxml_use_internal_errors(true);
$DOM->loadHTML($response);
$xpath = new DOMXPath($DOM);
$tbody = $DOM->getElementsByTagName('col-sm-7 tracking');
$query = '//li';
$entries = $xpath->query($query);
foreach ($entries as $entry) {
echo $entry->nodeValue . "<br>";
}
试图建立一个像这样的数组:
[0] => Array
(
[Title] => Text 1
[Info] => Text 1
[Time] => Text 1
)
[1] => Array
(
[Title] => Text 2
[Info] => Text 2
[Time] => Text 2
)
这使用XPath在每个<li>
标记下找到相关部分,以提取各种信息。要记住的事情是使用<li>
作为后续表达式的起点(将其作为第二个参数传递给XPath调用)。
某些电话中您只需要我用过的文本evaluate()
,因此它节省了获取文本的额外步骤...
foreach ($entries as $entry) {
$title = $entries = $xpath->evaluate('string(div[@class="title"])', $entry);
$info = $entries = $xpath->evaluate('string(div[@class="info"])', $entry);
$timeParts = $entries = $xpath->query('div[@class="time"]/span', $entry);
$time = [];
foreach ( $timeParts as $part ) {
$time[] = $part->textContent;
}
$output[] = [ "title" => $title, "info" => $info,
"time" => implode(" ", $time) ];
}