Issue
I just use HTML Simple Parser to find news by typing words and got an issue on stripos()
my result got duplicated because i type keywords "Joe Antam".
Here my codes:
$data['inputcari'] = $this->input->post('inputcari');
$html = file_get_html('https://www.suara.com/bisnis/bisnis-category/keuangan');
$data['konten'] = $html->find('div[class="item-content item-right"]');
$data['terms'] = explode(' ', $data['inputcari']);
foreach ($data['konten'] as $kon) {
foreach ($data['terms'] as $term) {
foreach ($kon->find('h4') as $h4) {
if (stripos($h4->plaintext, $term) !== false) {
echo $h4->plaintext . '<br>';
}
}
}
}
it's make them display all results contain joe and then antam so the results make it twice, like this below:
Joe Biden Jadi Presiden AS, Apa Pengaruhnya ke Indonesia
Joe Biden Kamala Harris Dilantik, Harga Emas Antam Naik Jadi Rp 963.000
Joe Biden Kamala Harris Dilantik, Harga Emas Antam Naik Jadi Rp 963.000
Nilai Tukar Rupiah Menguat Usai Joe Biden Dilantik Jadi Presiden AS
Pelantikan Joe Biden Kamala Harris Berimbas Positif ke IHSG
Joe Biden Dilantik Jadi Presiden AS, Harga Emas Dunia Makin Berkilau
Solution
Rather than echo
ing out each line as you find it, adding them to an array and then at the end of the loop using array_unique()
to remove the duplicates before outputting them...
$lines = [];
foreach ($data['konten'] as $kon) {
foreach ($data['terms'] as $term) {
foreach ($kon->find('h4') as $h4) {
if (stripos($h4->plaintext, $term) !== false) {
$lines[] = $h4->plaintext;
}
}
}
}
$lines = array_unique($lines);
echo implode('<br>', $lines);
Or...
Swap the two inner loops, so your last loop is the terms, then break out of that loop as soon as a match is found...
foreach ($data['konten'] as $kon) {
foreach ($kon->find('h4') as $h4) {
foreach ($data['terms'] as $term) {
if (stripos($h4->plaintext, $term) !== false) {
echo $h4->plaintext;
break;
}
}
}
}
Answered By - Nigel Ren
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.