Parsing WordPress XML, slash:comments syntax?

This is really just a syntax question.

I have a PHP script that parses my WordPress feed and returns the latest posts. I also want my script to parse the # of comments, but the WordPress feed XML object for number of comments has a colon in it (slash:comments). It causes the following error:

Read More

Parse error: syntax error, unexpected
‘:’ in … on line …

I have tried each of the following without luck:

$xml->slash:comments

$comments = 'slash:comments'
$xml->$comments

$xml->slash.':'.comments
$xml->{slash:comments}
$xml->{'slash:comments'}

How do I parse an object with a colon?

Related posts

Leave a Reply

3 comments

  1. Alternatively, you can use xpath() to access the nodes. Given the following as an xml string:

    <entry>
      <id>http://gdata.youtube.com/feeds/api/videos/xyz12345678</id>
      <published>2007-01-17T23:41:00.000Z</published>
      <updated>2010-11-14T03:52:25.000Z</updated>
      <yt:location>Mount Washington Observatory, NH</yt:location>
      <media:group>
        <media:title type='plain'>Example of a Title</media:title>
        <media:duration seconds='126'/>
      </media:group>
    </entry>
    

    You could do this:

    $xml = simplexml_load_string(*xmlstring_from_above*);
    
    $location = $xml->xpath('yt:location');
    echo($location[0]); // output: "Mount Washington Observatory, NH"
    
    $title = $xml->xpath('media:group/media:title');
    echo($title[0]); // output: "Example of a Title"
    
    $duration = $xml->xpath('media:group/media:duration');
    echo($duration[0]['seconds']); // output: "126"
    

    As you can see, to get the nodes with colons, you may use xpath() with a relative path to the node.

  2. $string = file_get_contents("http://domain.tld/?feed=rss2");
    $string = str_replace('slash:comments','slashcomments',$string);
    
    $xml = simplexml_load_string($string);
    

    Use str_replace to remove the colons from the string and allow simplexml_load_string to function as normal.

    For example:

    $string = file_get_contents("http://domain.tld/?feed=rss2");
    $string = str_replace('slash:comments','slashcomments',$string);
    $xml = simplexml_load_string($string);
    foreach ($xml->channel->item as $val) {
        echo $val->pubDate.'<br />';
        echo $val->title.'<br />';
        echo $val->slashcomments.'<br /><br />';
    }
    

    … should return the published date, title, and number of comments of the posts listed in a WordPress feed. My code is more advanced, but this illustrates the workaround.

    Thank you, Arda Xi, for your help!