简体   繁体   中英

PHP xpath selection

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM