-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?

6
  • You should probably post that data to your PHP backend instead of loading the whole file and scraping it. Commented Jul 21, 2020 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! Commented Jul 21, 2020 at 11:21
  • And then, you need to go and read up on some regex basics. [.*] is the list of characters . and *. (regex101.com can offer a lot of help, if you’re still fuzzy on the details.) Commented Jul 21, 2020 at 11:24
  • @Cbroe, there is just this warning: Warning: preg_grep() expects parameter 2 to be array, string given Commented Jul 21, 2020 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 Commented Jul 21, 2020 at 11:48

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

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.