views:

226

answers:

2

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:

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?

A: 

A variable in PHP can never have a colon in it. Therefore, you should check your XML parser to see how it handles colons.

Arda Xi
I'm using simplexml_load_string. I just discovered the command var_dump(), and it looks like simplexml_load_string discards all elements with a colon in the title. So what I did was remove the colon from all instances of slashcomments.
A: 
$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!