I have a XML file simillar to this :
<information version="2">
<currentTime>2014-06-06 17:28:16</currentTime>
<result>
<name>Mark</name>
<surname>Smith</surname>
</result>
I read it with php function and parse it to the object with function, like this:
function parse_data($data){
$return_data['currentTime'] = $data->currentTime;
$return_data['name'] = $data->result->name;
$return_data['surname'] = $data->result->surname;
return $return_data;
}
$xml = simplexml_load_string(file_get_contents($link));
$object = parse_data($xml);
Then, when I echo it on the screen, to check how it look:
//json_encode($xml);
{
"#attributes":{"version":"2"},
"currentTime":"2014-06-06 17:28:16",
"result":{"name":"Mark","surname":"Smith"}
}
//print_r($xml);
SimpleXMLElement Object (
[#attributes] => Array ( [version] => 2 )
[currentTime] => 2014-06-06 17:56:30
[result] => SimpleXMLElement Object (
[name] => Mark
[surname] => Smith
)
)
//json_encode($object);
{
"currentTime":{"0":"2014-06-06 17:28:16"},
"name":{"0":"Mark"},
"surname":{"0":"Smith"}
}
//print_r($object);
Array (
[currentTime] => SimpleXMLElement Object ( [0] => 2014-06-06 17:52:50 )
[name] => SimpleXMLElement Object ( [0] => Mark)
[surname] => SimpleXMLElement Object ( [0] => Smith )
)
What is wrong with my code? He seems to read the informaton in xml file as array? Because of this strange notation I cannont operate on this data normally.
It also behave like this:
echo json_encode($object['name']); will give -> {"0":"Mark"}
echo $object['name']; will give -> Mark
Can anybody help me? What am I doing wrong?
I want my $object to look like this:
//json_encode($object);
{
"currentTime":"2014-06-06 17:28:16",
"name":"Mark",
"surname":"Smith"
}
Edit1: added print_r values
Yes, as you have noticed the type returned by $someSimpleXMLNode is an object. If you want the node value (as a string for example) use:
$return_data['currentTime'] = (string)$data->currentTime;
which is the same as doing
$return_data['currentTime'] = $data->currentTime->__toString();
etc
When you do
echo $data->currentTime;
the node is automatically coerced into a string (because echo only handles strings). This is done (generally, in php) by the object's __toString method.
Related
I'm using the namecheap API to do some stuff, it's the first time I've used a API and I'm running into a bit of a problem.
This is what I have so far:
$ApiKey = "**********************";
$ApiUser = "*****";
$UserName = "*********";
$ClientIP = "********";
$NamecheapURI = "https://api.namecheap.com/xml.response";
$executionURL = $NamecheapURI."?ApiUser=".$ApiUser."&ApiKey=".$ApiKey."&UserName=".$UserName."&Command=namecheap.domains.check&ClientIp=".$ClientIP."&DomainList=".$domain;
$xml = simplexml_load_file($executionURL);
print_r($xml);
When print $xml I am returned simple XML objects:
SimpleXMLElement Object
(
[#attributes] => Array
(
[Status] => OK
)
[Errors] => SimpleXMLElement Object
(
)
[Warnings] => SimpleXMLElement Object
(
)
[RequestedCommand] => namecheap.domains.check
[CommandResponse] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Type] => namecheap.domains.check
)
[DomainCheckResult] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Domain] => facebook.com
[Available] => false
[ErrorNo] => 0
[Description] =>
[IsPremiumName] => false
[PremiumRegistrationPrice] => 0
[PremiumRenewalPrice] => 0
[PremiumRestorePrice] => 0
[PremiumTransferPrice] => 0
[IcannFee] => 0
[EapFee] => 0
)
)
)
[Server] => PHX01APIEXT03
[GMTTimeDifference] => --5:00
[ExecutionTime] => 0.008
)
My question is beyond this, how do I move forward and pull data from this?
I've tried treating this as an array but I am getting nowhere, when using is_array() to test if it was an array it says it's not which I don't understand...
I apologise if this is a noob question, I am a bit new to this. In short, what do I need to do to pull data from this?
Thanks in advance!
Learning to use SimpleXML is much better than trying to convert it to arrays/json/anything else and simple (hence the name). A quick example...
$response = '<?xml version="1.0" encoding="UTF-8"?>
<CommandResponse Type="namecheap.domains.check">
<DomainCheckResult Domain="facebook.com">
<Element>1234</Element>
<Element>12345</Element>
</DomainCheckResult>
</CommandResponse>';
$xml = simplexml_load_string($response);
echo "DOmain=".$xml->DomainCheckResult['Domain'].PHP_EOL;
foreach ( $xml->DomainCheckResult->Element as $value) {
echo "Value=".(string)$value.PHP_EOL;
}
outputs...
DOmain=facebook.com
Value=1234
Value=12345
You have to adapt this to your own XML, but the idea is that if you want to access an element of an item you use object notation -> and if you need to get an attribute, use array notation [].
So in the above code, the first echo ($xml->DomainCheckResult['Domain']) gets the <DomainCheckResult> element and outputs the Domain attribute.
Then the foreach loop says fetch each <Element> within <DomainCheckResult> and output the value.
This question already has answers here:
SimpleXML get node value
(3 answers)
Closed 8 years ago.
SimpleXMLElement Object
(
[SMSMessage] => SimpleXMLElement Object
(
[Sid] => xyz
[DateUpdated] => 2013-05-02 18:43:19
[DateCreated] => 2013-05-02 18:43:19
[DateSent] => 1970-01-01 05:30:00
[AccountSid] => xx
[To] => 09011148771
[From] => xx
[Body] => Hello
[BodyIndex] => SimpleXMLElement Object
(
)
[Status] => sending
[Direction] => outbound-api
[Price] => SimpleXMLElement Object
(
)
[ApiVersion] => SimpleXMLElement Object
(
)
[Uri] => /v1/Accounts/xx/Sms/Messages/xyz
)
)
I tried:
$xml->Sid;
But it returns SimpleXMLElement Object ( )
I also tried $xml->title, which also returned the same SimpleXMLElement Object ( )
How to get the Sid from the above XMl
I've been Fiddling a bit and recreated a structure similar to yours:
$string='<?xml version="1.0"?>
<xml>
<SMSMessage>
<Sid>xyz</Sid>
<DateUpdated>2013-05-02 18:43:19</DateUpdated>
</SMSMessage>
</xml>';
$xml = new SimpleXMLElement($string);
print_r($xml);
this outputs:
SimpleXMLElement Object
(
[SMSMessage] => SimpleXMLElement Object
(
[Sid] => xyz
[DateUpdated] => 2013-05-02 18:43:19
)
)
Which is equal to yours. And I could print xyz doing:
echo $xml->SMSMessage->Sid;
Try it out, you might be missing some parent node or something.
Your Method: To do it the way you want, I think you'd have to go one step further with your call since the SimpleXMLObject is parent to another SimpleXMLObject. E.g. $xml->SMSMessage->Sid;. I generally recommend using xpath with XML because in most cases, you want to jump directly to a specific node and not traverse the whole XML tree. For example, this: $xml->xpath('//[node]') is quicker than $xml->tier1->tier2->tier3->etc.
Preferred Method: Assuming $xml represents the SimpleXMLObject you've posted, you can access Sid like this: $xml->xpath('//Sid');. This should skip directly to the "Sid" node in the tree.
In simplexml you always have to cast your values - so you have to do this:
echo $xml->Sid;
(echo automatically casts). Or explicitly:
$string = (string) $xml->id;
if you have:
$string='<?xml version="1.0"?>
<xml>
<SMSMessage>
<Sid>xyz</Sid>
<DateUpdated>2013-05-02 18:43:19</DateUpdated>
</SMSMessage>
</xml>';
$xml = new SimpleXMLElement($string);
print_r('<pre>');
$Sid = (array)($xml->SMSMessage->Sid);
print_r($Sid[0]);
print_r($xml);
You can access Sid like so $Sid = (array)(xml->SMSMessage->Sid); echo $Sid[0];
But if you rather use array you can do this:
$string='<?xml version="1.0"?>
<xml>
<SMSMessage>
<Sid>xyz</Sid>
<DateUpdated>2013-05-02 18:43:19</DateUpdated>
</SMSMessage>
</xml>';
$array= json_decode(json_encode(new SimpleXMLElement($string)), true);
print_r('<pre>');
print_r($array['SMSMessage']['Sid']);
print_r($array);
I'm currently using file_get_contents to get an xml.
It work well and when I display the xml with the correct MIME type header('Content-type: text/xml') I obtain something like this :
<?xml version="1.0" encoding="iso-8859-1" ?>
<tarification compagnie="banane" cle="laclef">
<gamme reference="equilibre-sante">
<tarif formule="f100">Xx.xx</tarif>
<tarif formule="f200">Xx.xx</tarif>
</gamme>
</tarification>
To use it as an object I use simplexml_load_string but when I print_r the returned object I didn't see the formule attribute I just see something like this :
SimpleXMLElement Object
(
[#attributes] => Array
(
[compagnie] => banane
[cle] => laclef
)
[gamme] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[reference] => equilibre-sante
)
[tarif] => Array
(
[0] => Xx.xx
[1] => Xx.xx
)
)
)
)
I want to get formule attributes, I have already tested to do this by following this tutorial without success.
You need to use the SimpleXMLElement::attributes as:
$xml = simplexml_load_string($xmlstring);
foreach($xml->gamme->tarif as $tarif) {
foreach($tarif->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
}
See it
I am going crazy here...
I already have a SimpleXMLElement Object so it is not an XML file...
I got it stored in a file object.txt
Now i want to put this object into a variable, but i can't get it to work...?
the SimpleXMLElement Object looks like this:
SimpleXMLElement Object
(
[PubmedArticle] => Array
(
[0] => SimpleXMLElement Object
(
[MedlineCitation] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Owner] => NLM
[Status] => In-Process
)
[PMID] => 20538400
[DateCreated] => SimpleXMLElement Object
(
[Year] => 2010
[Month] => 07
[Day] => 08
)
[Article] => SimpleXMLElement Object
(
[#attributes] => Array
(
[PubModel] => Print-Electronic
)
.....etc etc....
how do i put this into a variable??
i tried this:
$simplexml = file_get_contents('object.xml');
$simplexml should be an array
Loading simplexml from file: simplexml_load_file: $a = simplexml_load_file('object.xml');
If you need something else, please explain.
If your 'object.xml' file contains the above example and not actual XML, it looks a lot like you are using the results of a vardump, and you possibly wish to load that into a (or several) SimpleXMLElementObject(s)...
So, really, you have a string inside of a text file, and you want to parse out the contents. I found this: converting text file into xml using php? and thought it would be a good starting point.
$response = sendRequest($curl, doCreateDB($domainid, $dbname, $dbtype));
$responseXml = parseResponse($response);
function parseResponse($response_string)
{
$xml = new SimpleXMLElement($response_string);
if (!is_a($xml, 'SimpleXMLElement'))
throw new ApiRequestException("Cannot parse server response: {$response_string}");
return $xml;
}
full output
SimpleXMLElement Object
(
[#attributes] => Array
(
[version] => 1.5.0.0
)
[database] => SimpleXMLElement Object
(
[add-db] => SimpleXMLElement Object
(
[result] => SimpleXMLElement Object
(
[status] => error
[errcode] => 1007
[errtext] => Database with requested name already exists
)
)
)
)
Final output at above. Then I want to get specific node's value.
Eg: i want to get status node.
I tried a few ways, but can't seems to print out the specific data.
echo $responseXml->database->{add-db}->result->status; // (nothing come out)
etc...
Try this:
echo $responseXml->database->{'add-db'}->result->status;
Note the single quotes to select a hyphenated array item: {'...'}.
Try
echo (string)$responseXml->database->{add-db}->result->status;