3

Im trying to store the string value's of a list item on my website into a variable/array in PHP to do some conditional checks/statements with them. Am having a bit off difficulty getting the list item's string value using PHP, can anybody help?

This is the markup.

<div class="coursesListed">
<ul>
<li><a href="#"><h3>Item one</h3></a></li>
<li><a href="#"><h3>item two</h3></a></li>
<li><a href="#"><h3>Item three</h3></a></li>            
</ul>
</div>

What i want ideally is either a variable or array that holds the values "Item one", "Item two", "Item three".

RoseCoder
  • 63
  • 1
  • 1
  • 7
  • 1
    Well for a start, PHP works on a `name` attribute. So you might want to give your elements one of those :) – christopher Jul 14 '13 at 09:33
  • 1
    Are you trying to parse the HTML and retrieve the values in all the

    tags?

    – Amal Murali Jul 14 '13 at 09:34
  • You can do that with some JS + PHP. – Mohammad Areeb Siddiqui Jul 14 '13 at 09:37
  • Okay I can give them a name. Amal, you will have to excuse my ignorance, im fairly new to programming in PHP. Yes im trying to retrive the values in the H3 tags, but only the H3 tags in the class coursesListed. Does that make sense? – RoseCoder Jul 14 '13 at 09:38
  • @RoseCoder: Please make yourself comfortable about which kind of questions are valid to be asked. For example, in that general form, you should first look for existing material like [How do you parse and process HTML/XML in PHP?](http://stackoverflow.com/q/3577641/367456) and then let us know into which problems you ran into with that (if even any problem). Because each other user with a different website to parse could ask a new question then which does not turn out well. Thanks for taking care! – hakre Jul 14 '13 at 12:16

3 Answers3

5

Try this

$html = '<div class="coursesListed">
<ul>
<li><a href="#"><h3>Item one</h3></a></li>
<li><a href="#"><h3>item two</h3></a></li>
<li><a href="#"><h3>Item three</h3></a></li>            
</ul>
</div>';

$doc = new DOMDocument();
$doc->loadHTML($html);
$liList = $doc->getElementsByTagName('li');
$liValues = array();
foreach ($liList as $li) {
    $liValues[] = $li->nodeValue;
}

var_dump($liValues);
Manoj Yadav
  • 6,560
  • 1
  • 23
  • 21
  • 1
    @Ali use `DOMElement::getAttribute function` to get a attribute value. http://in3.php.net/manual/en/domelement.getattribute.php and I think you mean how to get `href` of `a` tag not `li` tag – Manoj Yadav Mar 26 '14 at 08:39
  • Yes Manoj, i meant to say that i have a `ul` of almost 65 `li` and every `li` has a link upon it. So what i want to do is to get only first 5 `li` in an array (along with the associated link) and print them along with the `href` associated with their respective `li`. Hope you get it :) – Ali Mar 27 '14 at 05:24
  • To get `href` of `a` in `li` try this `$li->getElementsByTagName('a')->item(0)->getAttribute('href')` or if `href` in `li` then try this `$li->getAttribute('href')` – Manoj Yadav Mar 27 '14 at 11:16