TransWikia.com

get javascript array/variable with php from html website

Stack Overflow Asked on November 4, 2021

I have this html text and need to extract mydata from html to php

<script>
var mydata=[{"id":105,"i":"4.jpg"},{id":13,"i":"5.jpg"}];
//some other js code
</script>

I tried this in php:

$html = file_get_contents($url);
$js = preg_grep("/var mydata={.*}/", $html);
$js = str_replace("var mydata=", "", $js );
$sv = json_decode($js);
print_r($sv);

Nothing is extracted. What am I doing wrong please?

P.S. I found similar topic here How to get Javascript variable from an HTML page?

One Answer

preg_match is solution:

$matches = array();
$js= preg_match("/var mydata=[.*]/", $html, $matches);
$match = str_replace("var mydata=", "", $matches[0]);
$sv = json_decode($match);
print_r($sv);

Answered by peter on November 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP