SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Apr 2009
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    SimpleXML -- how to use variables in a query??

    I'm trying to query a simplexml object to obtain attribute names and values. The following works -

    foreach($xml->book[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
    }
    but i want to make this query work dynamically and replace book with a variable but when I do I get the following error -

    Warning: main() [function.main]: Node no longer exists in /home/ . . . .

    My code works when I substitute the 0 after book with a variable which has had intval() used on it but not when I substitute book for a variable. Anyway, here's the code which is causing the errors -
    $xt = strval("book");
    $xno = intval(0);

    foreach($xml->$xt[$xno]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
    }
    I've tried all sorts of thing to get the string variable to run in the query including using strval, not using it, using it with quotes and without quotes. I am really stuck on this. Is it even right to use strval()? Or is there another method to get the variable to execute?

  2. #2
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,397
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    A quick fix would be to change $xt[$xno] to {$xt}[$xno]
    Salathe
    Software Developer and PHP Manual Author.

  3. #3
    SitePoint Member
    Join Date
    Apr 2009
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Salathe View Post
    A quick fix would be to change $xt[$xno] to {$xt}[$xno]
    Thank you that worked.

    I've got another question if you don't mind. I'd like to make the $xt variable equal to the value of a global variable but I'm getting -
    Fatal error: Call to a member function attributes() on a non-object in /home/.......

    I know global variables aren't recommended but do you have any suggestions on how I could make it work? the code is -


    $xt = $GLOBALS['selectedChild'];
    $xno = 0;

    foreach($xml->{$xt}[$xno]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
    }

  4. #4
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,397
    Mentioned
    65 Post(s)
    Tagged
    0 Thread(s)
    The error simply means there are no $selectedChild nodes and therefore we can't access the attributes of the first one. It's always better to make sure that things exist before trying to make use of them.
    Salathe
    Software Developer and PHP Manual Author.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •