Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top