0

I got a XML file, which got a structure like the following:

<outfits>
    <outfit name="1"></outfit>
    <outfit name="2"></outfit>
    <outfit name="3"></outfit>
    <outfit name="4"></outfit>
</outfits>

Now I want to select each <outfit> inside the <outfits> Tag. Been trying using the following PHP code.

$data  = self::request($files['outfits']); //returns url from another function
$data  = @simplexml_load_string($data); // Loads the XML into a string from the URL
$outfits = @$data->xpath('//outfits/*'); // Supposed to search the string using xpath

UPDATE

The function does look like the following actually:

  public static function get_outfits($username){
     $files = self::user_files($username);
     $data  = self::request($files['outfits']);
     $data  = @simplexml_load_string($data);
     if ($data && count(@$data->xpath('//outfit')) > 0){
        $outfits = @$data->xpath('//outfit');
        foreach($outfits as $outfit) {
           $response['outfits'] = array(
              "name" => (string)$outfit['name'],
              "color" => (string)$outfit['color'],
              "mood" => (string)$outfit['mood'],
              "species" => (string)$outfit['species']
           );
        }
     }
     else{
        echo 'User got no outfits.';
     }
     return (isset($response) ? $response : false);
  }

But sadly the response would always be empty. Does anyone have a clue why?

2
  • I think that is a typo, with it same "problem" Commented Sep 28, 2015 at 12:28
  • Yes sorry that's a typo. Corrected it. Commented Sep 28, 2015 at 12:30

1 Answer 1

2

The xml is parsed into an object with one array with key "outfit".

Try this code, for me it worked:

$myXMLData = '<outfits>
    <outfit name="1"></outfit>
    <outfit name="2"></outfit>
    <outfit name="3"></outfit>
    <outfit name="4"></outfit>
</outfits>';

$xml = simplexml_load_string($myXMLData);
foreach ($xml->outfit as $outfit){
    echo $outfit['name'];
}

using xpath you would get:

$outfits = @$xml->xpath('//outfit');
print_r($outfits);
Sign up to request clarification or add additional context in comments.

Comments

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.