0

I am quite new with PHP and I am trying to read something form an API. At the moment I use

$homepage = file_get_contents('http://www.site.com');
echo $homepage

This returns something which looks like this:

Array
(
    [0] => Array
    (
        [name] => myname
        [user_id] => 31232
    )
    [1] => Array
    (
        [name] => anothername
        [user_id] => 23534
    )
)

So here is what I want: I only want to read the [name] => x and leave the rest, so I tried a for loop within str_replace, but all I got were errors.

I hope someone is able to help me

Edit: I just saw I could set is as a json text too, it returns something like

[{"name":"myname","user_id":"31232"},{"name":"anothername","user_id":"23534"}]

Edit2: Thank you Tuga, that was exactly what I was searching for :) I can't upvote, since my reputaion is below 15, is there another way for me to show your answer helped?

  • show us this last code, what do you mean with read? – Markus Kottländer Jan 08 '14 at 21:33
  • an api returning a raw php array, not xml or /?? –  Jan 08 '14 at 21:35
  • So you are saying the contents of the URL are a PHP var_dump? Otherwise just running `echo $homepage` would not produce that sort of variable dump format. Are you not showing something? If you are working with some sort of API, then you should be able to get the data in some kind of structured format (XML, JSON, or some other serialized format). At that point you would just take the structured data and work with it in PHP rather than trying to parse values out of it as a string. – Mike Brant Jan 08 '14 at 21:35
  • possible duplicate of [Create array printed with print\_r](http://stackoverflow.com/questions/7025909/create-array-printed-with-print-r) – Markus Kottländer Jan 08 '14 at 21:36
  • Why are you using `str_replace`? What are you trying to do with that? Does `echo $homepage;` *really* give you that *exact* output? Or are you parsing it in some way before? What is the *exact* output the page is giving you and what *exactly* so you want to do with it. – gen_Eric Jan 08 '14 at 21:40
  • The API is probably giving you back a JSON string which can be parsed into an array that looks like that. Try something like: `$data = json_decode($homepage, TRUE); foreach($data as $x){ echo $x['name']; }` – gen_Eric Jan 08 '14 at 21:41
  • You should past the code exactly as you see it, you may also post the url. – Pedro Lobito Jan 08 '14 at 21:44

1 Answers1

0

$array = json_decode($homepage); will return an array, then you can loop the array containing objects and use 'name' attribute :

foreach ($array as $obj) echo $obj->name;

Damien
  • 644
  • 4
  • 11