Parsing WordPress XML syntax, forward slash: comments?

It's really just a matter of syntax.

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

Parse error: syntax error, unexpected ':' in ... on line ...

I've tried each of the following with no luck:

$xml->slash:comments

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

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

      

How do I parse an object using a colon?

+2


source to share


3 answers


Alternatively, you can use xpath () to access nodes. Considering 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 can do it:



$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 nodes with colons, you can use xpath () with a relative path to node.

+3


source


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



0


source


$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 colons from the string and allow simplexml_load_string to function as usual.

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 in posts listed in the WordPress feed. My code is more advanced, but this illustrates a workaround.

Thank you Arda C for your help!

0


source







All Articles