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

删除回忆录丶 提交于 2019-11-29 08:55:57

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

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

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

?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!