可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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".
回答1:
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);
回答2:
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');
回答3:
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"; ?>