Home > database >  Getting value using attribute in xml php
Getting value using attribute in xml php

Time:12-08

I am trying to get the value of result attribute which is 1 in from the code below.

$file  = file_get_contents('https://test.com/...'); 
$xml = simplexml_load_string($file)

var_dump($xml); 

gives following object

object(SimpleXMLElement)#1 (1) {
[0]=> string(141) "
    <response result="1"> 
       <message>Yes here</message>
    </response>"
 }

How will I be able to get the value of attribute result = '1'.

print_r($xml->response['result'];  //gives NULL

CodePudding user response:

Use the attributes method:

$file  = <<<XML
<response result="1">
    <message>Yes here</message>
</response>
XML;
$xml = simplexml_load_string($file);

echo $xml->attributes()[0]; # returns '1'

If there is only one attribute, the [0] can be dropped. If there is more than one, use [k] for the (k 1)-th attribute.

CodePudding user response:

You'll need to use the attributes method after you specified the tag name to get all the attributes of that tag. Then you can get the value of your desired attribute by specifying the attribute name.

$xml->response->attributes()['result']
  • Related