• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 585
  • Last Modified:

QueryPath PHP First Element

I'm running QueryPath thru an html file to extract a single link. I have the following code which displays all links on the page:

$qp = htmlqp('test.html', 'body');
$links = array ();
$textmatch = "mymatch/matched";
foreach ($qp->top('a[href]') as $item) {
  $links[] = $item->attr('href');
}

for ($i = 0; $i < count($links); ++$i) {
  if (strpos($links[$i],$textmatch) !== false) {
   echo $links[$i]."<br>", PHP_EOL;
}
}

Open in new window


How do I extract only the first match?
0
kjenney
Asked:
kjenney
  • 2
1 Solution
 
Julian HansenCommented:
Is this what you want
$qp = htmlqp('test.html', 'body');
$links = array ();
$textmatch = "mymatch/matched";
foreach ($qp->top('a[href]') as $item) {
  $link = $item->attr('href');
 if (strpos($link,$textmatch) !== false) break;
}

// first matched accessed through $links

Open in new window

0
 
kjenneyAuthor Commented:
Works beautifully! BTW: in the code $links is misspelled on line 5 and 6 as $link. Figured it out, though :) Thanks!
0
 
Julian HansenCommented:
Actually you don't need line 2

$links = array();

You are not saving the links only taking the first so that line can go - then the 5 and 6 lines make sense (I intentionally called the variable $link as we are now dealing with singular).

So you can delete line 2 and leave $link as $link

What is misspelled is the comment on line 9 - with the above in mind - that should be $link as well.

Thanks for the points!
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now