0

I'm having trouble getting this to work. I'm scraping a website using a xpath selector and this returns 38 results which are added to the array $list. Now the first 5 results and the last 3 are useless to me. What I need is to only add results 6-35 to the array. I've tried many different combinations of if, for and while conditionals but can't seem to get this to work. I'd love to hear what I'm doing wrong and finally get this to work.

$url = "www.theurl.com";
$html = new DOMDocument();
@$html->loadHtmlFile($url);
$xpath = new DOMXPath($html);

$nodelist = $xpath->query("//span[@class='mp-listing-title']");

$list = array();

$i = 0;

foreach ($nodelist as $n) {
  $i++;
}
if ($i >=5 && $i <=35) {
  $value = $n->nodeValue;
  $list[] = $value;
}

Thanks for your help!

2
  • 2
    you are closing foreach loop too early leaving the if condition out of the loop or is that a typo....? Commented Jul 18, 2017 at 10:54
  • You should put that as the answer @SudhirBastakoti Commented Jul 18, 2017 at 10:56

2 Answers 2

2

Try this, it can help you:

 $url = "www.theurl.com";
 $html = new DOMDocument();
 @$html->loadHtmlFile($url);
 $xpath = new DOMXPath($html);

 $nodelist = $xpath->query("//span[@class='mp-listing-title']");

 $list = array();

 $i = 0;

 foreach ($nodelist as $n) {
   if ($i >=5 && $i <=35) {
     $value = $n->nodeValue;
     $list[] = $value;
   }
   $i++;
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Since nodelist is obviously a list array, wouldn't it be more correct to use for($i=0; $i<count($nodelist); $i++) and then access $nodelist[$i]->nodeValue instead of foreach and then manually increment $i?
Here is a better desciprition of your question PHP for() VS foreach()
0

Try the following:

$url = "www.theurl.com";
$html = new DOMDocument();
@$html->loadHtmlFile($url);
$xpath = new DOMXPath($html);

$nodelist = $xpath->query("//span[@class='mp-listing-title']");

$list = array();

$i = 0;

foreach ($nodelist as $n)  {
  if ($i >=5 && $i <=35) {
    $value = $n->nodeValue;
    $list[] = $value;
  }
  $i++;
}

Your conditional was out side of the loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.