SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Thread: PHP & SimpleXML

  1. #1
    SitePoint Member
    Join Date
    Jul 2008
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP & SimpleXML

    Hi guys,
    what am I doing wrong here:

    PHP Code:
    <?php
        $file 
    'test.xml';
        
    $id '2';

        
    $xml simplexml_load_file($file);
        
    $path "/list/artist[@id=".$id."]/rank";
        
    $result $xml->xpath($path);
        
        echo 
    $result;
    ?>
    HTML Code:
    <?xml version="1.0" encoding="utf-8"?>
    
    <list>
    	<artist id="1">
    		<name>Edu Reyes</name>
    		
    		<rank>1</rank>
    		
    		<country>Spain</country>
    	</artist>
    
    	<artist id="2">
    		<name>Wally Lopez</name>
    		
    		<rank>2</rank>
    		
    		<country>Spain</country>
    	</artist>
    
    	<artist id="3">
    		<name>Danny Tenaglia</name>
    		
    		<rank>3</rank>
    		
    		<country>United States</country>
    	</artist>
    </list>
    As an echo I get the word Array. I want to echo the value between the rank tags. In my example above I want the ranking of the artist with the id 2 (which would echo 2).

    Thanks,
    Max

  2. #2
    SitePoint Guru risoknop's Avatar
    Join Date
    Feb 2008
    Location
    end($world)
    Posts
    834
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    <?php 

        $file 
    'test.xml'
        
    $id '2'

        
    $xml simplexml_load_file($file); 
        
    $path "/list/artist[@id=".$id."]/rank"
        
    $result $xml->xpath($path); 
         
        foreach (
    $result as $value)
          echo 
    $value

    ?>
    Richard

  3. #3
    SitePoint Member
    Join Date
    Jul 2008
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you! Works! Is there a better way to do this? I have a pretty big XML file. Maybe someting that needs less resources?

    Thanks,
    Max

  4. #4
    SitePoint Guru risoknop's Avatar
    Join Date
    Feb 2008
    Location
    end($world)
    Posts
    834
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, I am not XML expert, to be honest. xpath() searches for all results fitting the description and it returns an array.

    So you have to use foreach to loop through the array.

    Or you could just echo only the first result:

    PHP Code:
    <?php 

        $file 
    'test.xml'
        
    $id '2'

        
    $xml simplexml_load_file($file); 
        
    $path "/list/artist[@id=".$id."]/rank"
        
    $result $xml->xpath($path); 
          
        echo 
    $result[0]; 

    ?>


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
  •