user11093829
user11093829

Reputation: 1

How to get span text in in php variable?

<span class="cid"></span>

In the above span, i am getting id from .js file. eg., 45 and i want that id in php variable. eg., $cid='45';

I have already tried below code, but i am unable to get id.

<?php echo $cid='<span class="cid"></span>'; ?>

<?php
    $str = $cid;

    $DOM = new DOMDocument;
    $DOM->loadHTML($str);

    $items = $DOM->getElementsByTagName('span');
    $span_list = array();

    for($i = 0; $i < $items->length; $i++) {
        $item = $items->item($i);
        $span_list[$item->getAttribute('class')] = $item->nodeValue;
    }
    extract($span_list);

    echo $cid; 
?>

Upvotes: 0

Views: 5861

Answers (3)

JJJJ
JJJJ

Reputation: 1358

Add an AJAX code to pass it to PHP

$.ajax({
    url: 'your_php_file.php',
    method: 'POST',
    data: {cid: $('.cid')[0].innerText},
    success: function(result){
        console.log(result);
    }
})

And in your PHP file. You can just use strip_tags

 echo strip_tags($_POST['cid']);

Upvotes: 0

Bhavin Thummar
Bhavin Thummar

Reputation: 1293

Please try the below code and check at your end you can get class value in the array.

Second time Update code

    <?php 
    echo $cid='<span class="cid">45</span>'; 
?>

<?php
    $str = $cid;

    $DOM = new DOMDocument;
    $DOM->loadHTML($str);

    $items = $DOM->getElementsByTagName('span');
    $span_list = '';

    for($i = 0; $i < $items->length; $i++) {
        $item = $items->item($i);

        if($item->getAttribute('class') == 'cid'){
            $span_list = $item->nodeValue;
        }
    }

    echo $span_list;
?>   

Code for multiple span tags and get single value from that span list array.

    <?php 
    $cid='<span class="cid">45</span> <span class="cid">48</span>'; 
?>

<?php
    $str = $cid;

    $DOM = new DOMDocument;
    $DOM->loadHTML($str);

    $items = $DOM->getElementsByTagName('span');
    $span_list = array();

    for($i = 0; $i < $items->length; $i++) {
        $item = $items->item($i);

        if($item->getAttribute('class') == 'cid'){
            $span_list[] = $item->nodeValue;
        }
    }

    //get the each value for multiple span tag

    foreach ($span_list as $key => $value) {
        echo $value;
        echo '<br/>';       
    }

?>

Upvotes: 1

PHP Geek
PHP Geek

Reputation: 4033

try this one add span text in php code to get the span value in variable

<?php
$value = '<span class="cid"></span>';
?>
echo $value

Upvotes: 2

Related Questions