{"flag":true,"single":true,"pageTitle":"Extract js variable value from html in PHP","post":{"id":168,"user_id":"1","slug":"extract-js-variable-value-from-html-in-php-rrpm","title":"Extract js variable value from html in PHP","body":"<pre class=\"language-markup\"><code>&lt;?php\r\n$html = '\r\n&lt;footer class=\"footer text-muted\"&gt;\r\n&lt;\/footer&gt;\r\n&lt;script&gt;\r\n    const dataModel = {\"application\":{\"applicationId\":1234, \/* ... *\/ }};\r\n&lt;\/script&gt;\r\n&lt;script type=\"text\/javascript\" src=\"\/Personal\/Portal\/ab.js\"&gt;&lt;\/script&gt;\r\n';\r\n\r\n$dom = new DOMDocument();\r\nlibxml_use_internal_errors(true); \/\/ Suppress warnings for invalid HTML\r\n$dom-&gt;loadHTML($html);\r\nlibxml_clear_errors();\r\n\r\n\/\/ Use XPath to extract the script containing dataModel\r\n$xpath = new DOMXPath($dom);\r\n$dataModelScript = $xpath-&gt;query('\/\/script[contains(text(), \"dataModel\")]')-&gt;item(0);\r\n\r\nif ($dataModelScript) {\r\n    $scriptContent = $dataModelScript-&gt;textContent;\r\n    preg_match('\/const dataModel = (\\{.*\\});\/', $scriptContent, $matches);\r\n    if (isset($matches[1])) {\r\n        $dataModelJson = $matches[1];\r\n        $dataModel = json_decode($dataModelJson, true);\r\n        print_r($dataModel);\r\n    }\r\n}\r\n?&gt;<\/code><\/pre>","category_id":"1","is_private":"0","created_at":"2023-08-15T00:20:46.000000Z","updated_at":"2023-08-15T00:20:46.000000Z","category":{"id":1,"user_id":"1","name":"PHP","slug":"php-3ius","parent_id":null,"created_at":"2023-03-14T03:58:19.000000Z","updated_at":"2023-03-14T03:58:19.000000Z"},"user":{"id":1,"name":"R GONDAL","email":"rizikmw@gmail.com","email_verified_at":null,"two_factor_confirmed_at":null,"current_team_id":"1","profile_photo_path":null,"created_at":"2023-03-12T10:49:33.000000Z","updated_at":"2025-01-10T12:59:00.000000Z","profile_photo_url":"https:\/\/ui-avatars.com\/api\/?name=R+G&color=7F9CF5&background=EBF4FF"}},"pageDesc":"&lt;?php $html = ' &lt;footer class=\"footer text-muted\"&gt; &lt;\/footer&gt; &lt;script&gt;     const dataModel = {\"application\":{\"applicatio - Extract js variable value from html in PHP (Updated: August 15, 2023) - Read more about Extract js variable value from html in PHP at my programming site [SITE]","categories":[]}