I am trying to get the title, info and time into array. However, I am stuck at getting the data. As you can see in my controller, I use getelementbyID to call my first-list, but it shows me the DOMElement Object. Can anyone help? :/
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>";
}
Trying to build an array like:
[0] => Array
(
[Title] => Text 1
[Info] => Text 1
[Time] => Text 1
)
[1] => Array
(
[Title] => Text 2
[Info] => Text 2
[Time] => Text 2
)
This uses XPath to find the relevant parts underneath each <li>
tag to extract the various pieces of information. The thing to remember is to use the <li>
as the start point for the subsequent expressions (pass it as the second parameter to the XPath call).
Some calls where you just need the text I've used evaluate()
so it saves an extra step to get the text...
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) ];
}