3

I need to parse the text out of an h3 element on an HTML page and save the text into a variable.

<h3 class="names-header">Names</h3>

I need the output:

Names

Saved into a variable like

$text = $output;

I've tried using DOMs, specifically this example but I've had no luck.

I've also tried to extract the data using JQuery, and submitting it as a post using Ajax on the same page. Then grabbing the post and saving it in PHP. This also didn't work, and it seems like there is a much quicker way to do this.

I've googled and tried for around 2 hours now and still can't figure out how to fix it. Any help/advice would be greatly appreciated right now. Thank you.

Community
  • 1
  • 1
Justin
  • 39
  • 1
  • 8
  • 1
    Define "didn't work". What makes you unable to parse HTML using PHP and traverse the generated tree? – Ram Jul 30 '15 at 05:05
  • @Vohuman Well one of my beginning problems was trying to load the html in. Like so: '$dom_document = new DOMDocument(); $dom_document->loadHTML($html);' – Justin Jul 30 '15 at 05:07
  • Possible duplicate http://stackoverflow.com/questions/5163197/how-to-get-element-id-into-php-variable – Maytham Fahmi Jul 30 '15 at 05:08
  • @ArjitaMitra Yes this is for Jquery/Javascript, but I need the value to be used in PHP. – Justin Jul 30 '15 at 05:09

1 Answers1

1

it would be easy to use jquery to do this! just use ajax like in the following code.

$.ajax({
   type: 'POST',
   url:'your php page',
   data:{name: $('.names-header').text()},
   success:function(response){
      alert(response);
   }
})

in you php do the following.

if(isset($_POST['name'])){
   echo $_POST['name'];
}else{
   echo 'no data to show';
}

this will allow you to catch the post data and do what ever you want.

Imesh Chandrasiri
  • 5,558
  • 15
  • 60
  • 103
  • 1
    `val` is used for getting/setting value of form elements not for getting `textContent` of elements. You should use the `text` method. – Ram Jul 30 '15 at 05:12
  • The text needs to be used on the same page, sorry for not clarifying it originally. – Justin Jul 30 '15 at 05:12
  • 1
    my suggestion is, separate your php logic from the page itself on to a separate file, then using ajax call the php page, do what ever you want there and return the processed to the ajax success. Then using javascript and jquery do what ever you want to the processed data which comes from the php page on to your current page. – Imesh Chandrasiri Jul 30 '15 at 05:18
  • @DimalChandrasiri I just finished working together, and doing some basic coding and I got it working! Thank you so much! – Justin Jul 30 '15 at 05:37