RoseCoder
RoseCoder

Reputation: 65

Get ul li a string values and store them in a variable or array php

I'm trying to store the string values of a list item on my website into a variable/array in PHP to do some conditional checks/statements with them. I am having a bit of 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".

Upvotes: 4

Views: 14896

Answers (3)

zpr
zpr

Reputation: 2940

It might be easier to parse it in Javascript (perhaps using jQuery), and then send it to your PHP with some AJAX.

// Javascript/jQuery
var array = [];
$("h3").each(function() {
    array.push($(this).html());
});

var message = JSON.stringify(array);
$.post('test.php', {data: message}, function(data) {
    document.write(data); // "success"
}

Then in PHP:

<?php

$data = $_POST['data'];

// convert json into array
$array = json_decode($data);

// do stuff with your data
// then send back whatever you need

echo "success";

?>

Upvotes: 1

Manoj Yadav
Manoj Yadav

Reputation: 6612

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);

Upvotes: 5

Satish Gadhave
Satish Gadhave

Reputation: 2970

You will need to parse the HTML code get the text out. DOM parser can be used for this purpose.

   $DOM = new DOMDocument;
   $DOM->loadHTML($str); // $str is your HTML code as a string

   //get all H3 
   $items = $DOM->getElementsByTagName('h3');

Upvotes: 2

Related Questions