-1

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?

peter
  • 4,289
  • 12
  • 44
  • 67
  • You should probably post that data to your PHP backend instead of loading the whole file and scraping it. – Kyrre Jul 21 '20 at 11:21
  • _“What am I doing wrong please?”_ - for startes, you apparently must be “developing”, without having proper PHP error reporting enabled. So go and do that first of all! – CBroe Jul 21 '20 at 11:21
  • And then, you need to go and read up on some regex basics. `[.*]` is the list of characters `.` and `*`. (https://regex101.com/ can offer a lot of help, if you’re still fuzzy on the details.) – CBroe Jul 21 '20 at 11:24
  • @Cbroe, there is just this warning: Warning: preg_grep() expects parameter 2 to be array, string given – peter Jul 21 '20 at 11:40
  • and now I updated my regex to /var mydata=\\[.*\\]/ and it works on regex101.com but always the same error on php script – peter Jul 21 '20 at 11:48
  • `preg_grep( string $pattern, array $input...` and you're dishing it a string, that's why you get an error. – Markus AO Jul 21 '20 at 18:32

1 Answers1

1

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);
peter
  • 4,289
  • 12
  • 44
  • 67