0

Using SimpleXML in PHP, I would like to grab ONLY the <lj:reply-count> node value.

XML:

<lj:security>public</lj:security>
<lj:posterid>631636</lj:posterid>
<lj:reply-count>42</lj:reply-count>

Sort of like this, but obviously not exactly this since it will throw php parse errors

if($item->lj:reply-count)
    $replyCount = $item->lj:reply-count

I tried a few other variations and Google'd around, but couldn't seem to find what I'm looking for. Thanks.

Kevin
  • 41,694
  • 12
  • 53
  • 70
EyeOfTheHawks
  • 576
  • 1
  • 5
  • 16

2 Answers2

1

Since your xml has namespaces, you have to use ->children() method for that. Example:

$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:lj="http://www.example.com/">
<lj:security>public</lj:security>
<lj:posterid>631636</lj:posterid>
<lj:reply-count>42</lj:reply-count>
</root>
XML;

$xml = simplexml_load_string($xml_string);
$lj = $xml->children('lj', 'http://www.example.com/');
$reply_count = (string) $lj->{'reply-count'};

echo $reply_count; // 42
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • Can i call children() recursively? For instance, calling $item->children() where $item is a specific item node? I dont see why i couldn't (no access to my code atm) – EyeOfTheHawks Jul 25 '14 at 04:24
  • @EyeOfTheHawks what do you mean by that? are you going to use this inside a loop? it's really hard to analyze things on this side since there's no context and obviously the xml is somewhat truncated. this method returns (returns another set of xml object) the children of that given nodes, this does not access directly your specifically desired item node – Kevin Jul 25 '14 at 04:28
  • That answers my question, thank you. I will accept one of these answers tomorrow when i am able to fully test them :D – EyeOfTheHawks Jul 25 '14 at 04:30
  • @EyeOfTheHawks if you want them directly, maybe you could just use something like `echo $xml->children('lj', 'http://www.example.com/')->{'reply-count'}; // echoes 42` – Kevin Jul 25 '14 at 04:31
0

This should work:

if($item->{"lj:reply-count"})
    $replyCount = $item->{"lj:reply-count"}
idmean
  • 14,540
  • 9
  • 54
  • 83