0

I am trying to pass HTML using QueryPath. I would like to get the value of a Javascript variable in the HTML. Like this:

<script type="text/javascript">

        var base_url = "http://www.exampleurl.com/";
        var room_id = "357"; //I want to get the value of room_id
        var selected_room_button = "";

</script>

I want to get value of Javascript variable *room_id* which is 357 How can I achieve this?

Even if not using QueryPath, are there any other HTML parsers that can enable me to do this kind of parsing?

1 Answer 1

4

You can use a regular expression. This code will return the room id in your example.

<?php

$html = '
<script type="text/javascript">
    var base_url = "http://www.exampleurl.com/";
    var room_id = "357"; //I want to get the value of room_id
    var selected_room_button = ""; 
</script>';

$pattern = '/var room_id = "(.*)";/';
preg_match($pattern, $html, $matches);
$room_id = $matches[1];

But there is no general solution as a variable may have been defined twice, or have been defined in different scopes.

If you don't need to extract other content beside the row_id I would see no reason for using a HTML parser. It would just slow down things. Also please expect the HTML parser not being a Javascript parser! The HTML parser would just being used to extract the unparsed content between <script> </script> tags - as a string. You would need a regex again to extract the row_id.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate. I think this should work. If no other more HTML-parser-native method comes up, this is my accepted answer for sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.