Skip to content
Advertisement

Get an array in a php file from http request

I’m learning php and I’m trying to get a php file from a http request using Guzzle and then just take a particular array from those contents and ignore the rest. But I’m unsure how to get that array.

<?php 
require_once "vendor/autoload.php";

use GuzzleHttpClient;

$client = new Client();
$response = $client->request('GET', 'http://api-address/file.php');

$body = $response->getBody();
$decoded = json_decode($body, true);

$contents = file_get_contents($decoded);

When I print $contents it looks as expected, for example:

<?php

$var = "example string";

$array = [
   [
      'name' => 'stuff I need'
   ]
];

I want to just get the array, iterate through it and write each to a file but I don’t know how to get just that and ignore the other stuff that isn’t in that array it if that makes sense. Any help would be appreciated.

Advertisement

Answer

You are using …

json_decode($body, true);

That method converts the content to array, that means that probably if you do a …

var_dump($decoded);

you can see an array that it contents arrays inside …

Well, I mean, you can get …

$array = [
 [
 'name' => 'stuff I need'
 ]
];

Navigating into $json_decode() array.

If you are asking the how, well, just use the next step …

$contentArray = $decoded[1] //With this you can get the array that you need.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement