1

I have a little problem:

I have this XML-File:

<response>
    <game_count>768</game_count>
    <games>
        <message>
            <appid>730</appid>
            <playtime_forever>549</playtime_forever>
        </message>
        <message>
            <appid>1300</appid>
            <playtime_forever>0</playtime_forever>
        </message>
        <message>
            <appid>1309</appid>
....

I tried to search for the value appid == '730' but unfortunately nothing helped.

E.G i tried this:

$game = new SimpleXMLElement($account_game_data);
$res = $game->xpath("games/message/appid[. = 730]");
print_r($res);

My result should be <appid>730</appid><playtime_forever>549</playtime_forever></message> as SimpleXMLElement.

If there is any code required, I will post it.

2
  • in your final result the sibling tag is also captured, should it be so? Commented Mar 16, 2017 at 21:16
  • @RomanPerekhres It works very fine. At least i had one fault, which isn't regarding to your code. It causes, that the game-var was empty. Thanks for help Commented Mar 18, 2017 at 23:08

1 Answer 1

2

Use the following approach:

$game = new \SimpleXMLElement($account_game_data);
$res = $game->xpath('games/message[appid="730"]');
print_r($res[0]->asXML());

The output:

<message>
            <appid>730</appid>
            <playtime_forever>549</playtime_forever>
        </message>

message[appid="730"] - matches the message element which has child appid with value 730

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

4 Comments

instead of selecting the parent with .., you can put the end of the path in the predicate: games/message[appid="730"]. You can even select the children of the first "message" that matches: games/message[appid="730"][1]/* ( then you have to loop over them to display them with SimpleXMLElement::asXML())
Strange, I don't have this problem: eval.in/755883 (perhaps take care of the quotes I used).
You need to remove the slash before the predicate.
@CasimiretHippolyte, that's enough for me today(GMT +02:00. late night). Your suggestion is correct. I've updated to your expression. Thanks

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.