-1

Please look at this code and help me to how to echo json_encode?

i want to get text of some tags in any website and send with json encode to application.

<?php
    $html = file_get_contents("any url");
    echo $html;
?>

<script>
    var td = document.getElementsByClassName("jumbotron");
    var h1 = td[0].getElementsByTagName("h1");
    var tmn = h1[0].innerHTML;
    tmn = tmn.trim();
    console.log(tmn);
</script>

<?php
    $name = "<script>document.writeln(tmn);</script>";
    $result = Array("name" => $name);
    header("Content-Type: application/json");
    echo json_encode($result);
?>

i expect the output of this code to be {"name":result} but this error showing:

Warning: Cannot modify header information - headers already sent by (output started at /opt/lampp/htdocs/apps/GetContent/index3.php:3) in /opt/lampp/htdocs/apps/GetContent/index3.php on line 18 {"name":"

Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34
MBR_H
  • 1
  • 1

1 Answers1

0

This happens when you are outputting before setting the header.

In the below code you are outputting the contents of $html.

<?php
$html = file_get_contents("any url");
echo $html;
?>

After this code has run, and there is information on-screen, you are setting the header to application/json:

<?php
$name = "<script>document.writeln(tmn);</script>";
$result = Array("name" => $name);
header("Content-Type: application/json");
echo json_encode($result);
?>

You can't do this, if you re-jig the order of your code then this will start working for you, for example:

<script>
    var td = document.getElementsByClassName("jumbotron");
    var h1 = td[0].getElementsByTagName("h1");
    var tmn = h1[0].innerHTML;
    tmn = tmn.trim();
    console.log(tmn);
</script>

<?php
$html = file_get_contents("any url");
$name = "<script>document.writeln(tmn);</script>";
$result = Array("name" => $name);
header("Content-Type: application/json");

echo json_encode($result);
echo $html;
?>
Mark
  • 1,852
  • 3
  • 18
  • 31