1

I have this javascript array

[
  "spiderman",
  "xmen",
  "barbie",
  "avengers"
]

It is what I see on the screen when I open http://localhost:8080

If I decide to show it in laravel using this code in a controller :

    public function showReccPosts(){
        $name='alice';

        // Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, [
    CURLOPT_URL => "http://localhost:8080/?name=$name",
    CURLOPT_PROXY => '',
]);
// Send the request & save response to $resp
$results = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

       return view('reccomended.index',compact('results'));

    }

}

And in a blade file: {{$results

I get:

[
  "spiderman",
  "xmen",
  "barbie",
  "avengers"
]1

What is up with the 1 attached at the end of the array? Will it stop me from from performing functions on the array? By the way,can I even use that type of array (from js to php)?

Turbo
  • 124
  • 11

1 Answers1

1

Your CURL request isn't returning the content to your PHP code and is probably just displaying it. You then are taking the return from CURL (the 1) to say it succeded and then displaying that. Change the options to capture the return value by setting CURLOPT_RETURNTRANSFER...

curl_setopt_array($curl, [
    CURLOPT_URL => "http://localhost:8080/?name=$name",
    CURLOPT_PROXY => '',
    CURLOPT_RETURNTRANSFER => true
]);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Thanks.It removed the `1` but gave me this: [ "spiderman", "xmen", "barbie", "avengers" ] Is there any way I can safely transferthe array from nodejs to php and php will still treat it as an arraY? – Turbo May 18 '19 at 06:52
  • You can use something like `html_entity_decode()` on `$results` to convert it. – Nigel Ren May 18 '19 at 06:56
  • If you need to manipulate it in PHP - you can then have a read of https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php – Nigel Ren May 18 '19 at 06:57
  • But php treats it as a string – Turbo May 18 '19 at 07:00
  • But it is not json.It is a js array which is converted to a string by php – Turbo May 18 '19 at 07:01