Search code examples
phparrayssimple-html-dom

how do i create an array of a string object in php?


i want to create an array of variable $link to get all the links in array so that i can process them simultaneously outside curly braces

include("simple_html_dom.php");


$html = file_get_html($url);

$i=0;
$linkObjs = $html->find('h3.r a'); 
foreach ($linkObjs as $linkObj) 
{
    $title = trim($linkObj->plaintext);
    $link  = trim($linkObj->href);

    //if it is not a direct link but url reference found inside it, then extract
    if (!preg_match('/^https?/', $link) && preg_match('/q=(.+)&sa=/U', $link, $matches) && preg_match('/^https?/', $matches[1])) 
    {
        $link = $matches[1];
    } else if (!preg_match('/^https?/', $link)) { // skip if it is not a valid link
        continue;
    }

   $descr = $html->find('span.st',$i); // description is not a child element of H3 thereforce we use a counter and recheck.
   $i++;   
}

Solution

  • Create an array and push matches.

    include("simple_html_dom.php");
    
    
    $html = file_get_html($url);
    
    $links = array();
    $i=0;
    $linkObjs = $html->find('h3.r a'); 
    foreach ($linkObjs as $linkObj) 
    {
        $title = trim($linkObj->plaintext);
        $link  = trim($linkObj->href);
    
    
      //   if it is not a direct link but url reference found inside it, then extract
    if (!preg_match('/^https?/', $link) && preg_match('/q=(.+)&sa=/U', $link, $matches) && preg_match('/^https?/', $matches[1])) 
    {
       array_push($links, $link);        
     } else if (!preg_match('/^https?/', $link)) { // skip if it is not a valid link
       continue;
       }
    
    $descr = $html->find('span.st',$i); // description is not a child element of H3 thereforce we use a counter and recheck.
    $i++;   
    }