file_get_contents() error!

Asked

Viewed 155 times

-1

I have the html form:

<div id="formulario">
        <form method="POST" action="Controller/jsonTeste.php">
            CEP: <input type="text" name="cep" placeholder="Insira o cep" required/>
            <input type="submit" /></p>
        </form>
</div>

And the php file:

<?php
$formCEP = $_POST['cep'];
$formCEP = preg_replace("/[^0-9]/", "", $formCEP);
$url = file_get_contents('http://viacep.com.br/ws/$formCEP/json/');
?>

When passing the $formCEP variable to the ULR: http://viacep.com.br/ws/$formCEP/json/, I receive a "Warning" as response, but when typing a valid zip code for the URL, it is accepted as valid. How to resolve?

  • Which Warning you get?

  • I think the problem is only the use of the variable $formCEP Concatenates it into the URL $url = file_get_contents('http://viacep.com.br/ws/' . $formCEP . '/json/');

1 answer

1


You are not replacing the $formCEP in your String. When you use single quote strings, interpolation does not work. To resolve, use double quotes.

<?php

$formCEP = "15047200";
$formCEP = preg_replace("/[^0-9]/", "", $formCEP);

echo 'http://v...content-available-to-author-only...m.br/ws/$formCEP/json/';
echo "\n";
echo "http://v...content-available-to-author-only...m.br/ws/$formCEP/json/";

Therefore, to work, change

$url = file_get_contents('http://viacep.com.br/ws/$formCEP/json/');

for

$url = file_get_contents("http://viacep.com.br/ws/$formCEP/json/");

Code working: https://ideone.com/Pkz2HC

  • Thank you! After the change, it worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.