User
User

Reputation: 21

How to display an array in PHP?

This is the code I currently have:

<?php
 echo file_get_contents("http://example.com/bin/serp.php?engine=google&phrase=stackoverflow&format=ARRAY");
?>

It is displaying this on my page:

Array
(
[0] => Array
    (
        [idx] => 0
        [title] => Stack Overflow
        [description] => A language-independent collaboratively edited question and answer site for programmers.
        [url] => http://stackoverflow.com/
    )

[1] => Array
    (
        [idx] => 1
        [title] => Stack Overflow - Wikipedia, the free encyclopedia
        [description] => Stack Overflow website logo.png &middot; Stack Overflow.png. Screenshot of Stack Overflow as of December 2011. Web address &middot; stackoverflow.com. Commercial? Yes.
        [url] => http://en.wikipedia.org/wiki/Stack_Overflow
    )
)

What do I need to change to have it displayed like this instead?

1.  <a href="http://stackoverflow.com/">Stack Overflow</a>
A language-independent collaboratively edited question and answer site for programmers.

2.  <a href="http://en.wikipedia.org/wiki/Stack_Overflow">Stack Overflow - Wikipedia, the free encyclopedia</a>
Stack Overflow website logo.png &middot; Stack Overflow.png. Screenshot of Stack Overflow as of December 2011. Web address &middot; stackoverflow.com. Commercial? Yes.

Any help with this would be highly appreciated.

Upvotes: 0

Views: 68

Answers (2)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146430

The print_r() function is a debug helper. It isn't intended as serialisation format:

  • There aren't built-in parsers (and it isn't trivial to write a robust one)
  • It can cause data loss, e.g.:

    $data = array(true, 1, false, 0, '');
    print_r($data);
    
    Array
    (
        [0] => 1
        [1] => 1
        [2] => 
        [3] => 0
        [4] => 
    )
    

You have this in the URL:

format=ARRAY

Just look at whatever place you use $_GET['format']. You'll possibly have more useful formats to choose from. If you don't, it'll be trivial to implement a sensible format, e.g. JSON.

Upvotes: 1

Amit Horakeri
Amit Horakeri

Reputation: 745

You can use the foreach control statement of PHP in order to achieve this, and here it goes:

Say that the $array is the resultant of file_get_contents and supposing that it holds the result to be displayed.

    <?php foreach($array as $arr){?>
     <a href="<?php echo $arr['url'];?>"><?php echo $arr['title'];?></a>
     <?php echo $arr['description']; ?>
    <?php } ?>

Hope this helps you....

Upvotes: 0

Related Questions