Saturday, February 19, 2022

[FIXED] Show Data Result Match by Array String PHP

Issue

Learning scrape with PHP simple DOM parser two days ago, but have an issue "strpos(): needle is not a string or an integer" while finding result by specific words given by array like codes below. What i have missed?

$this->load->library('simple_html_dom');
$html = file_get_html('https://id.priceprice.com/harga-hp/');

$konten = $html->find('h3');
$keyword = array('Samsung', 'Huawei', 'Iphone');

foreach ($konten as $e) {
   if (strpos($e->plaintext, $keyword) !== false) {
       echo $e->plaintext . "</br>";
   }
}

error message, as per OP's comment:

strpos(): needle is not a string or an integer


Solution

$keyword is an array, you need to foreach() loop through it, e.g.:

foreach ($konten as $e) {
  foreach ($keyword as $kw) {
    if (strpos($e->plaintext, $kw) !== false) {
        echo $e->plaintext . "</br>";
    }
  }
}

see php function strpos():

strpos ( string $haystack , string $needle , int $offset = 0 ) : int|false



Answered By - Vickel

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.