2

I am trying to create an array of titles from an xml feed using this code:

$url = 'https://indiegamestand.com/store/salefeed.php';
$xml = simplexml_load_string(file_get_contents($url));

$on_sale = array();

foreach ($xml->channel->item as $game)
{
    echo $game->{'title'} . "\n";
    $on_sale[] = $game->{'title'};
}

print_r($on_sale);

The echo $game->{'title'} . "\n"; returns the correct title, but when setting the title to the array i get spammed with this:

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => SimpleXMLElement Object
                (
                )

        )

    [1] => SimpleXMLElement Object
        (
            [0] => SimpleXMLElement Object
                (
                )

        )

    [2] => SimpleXMLElement Object
        (
            [0] => SimpleXMLElement Object
                (
                )

        )

Am I missing something when setting this array?

1 Answer 1

2

Use this:

$on_sale[] = $game->{'title'}->__toString();

or even better (in my opinion):

$on_sale[] = (string) $game->{'title'};

PHP doesn't know that you want the string value when you add the object to the array, so __toString() doesn't get called automatically like it does in the echo call. When you cast the object to string, __toString() is called automatically.

FYI: You don't really need the curly braces either, this works fine for me:

$on_sale[] = (string) $game->title;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.