How to get an element from simplexml [duplicate] - php

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

Related

Fetch specific tag value from response object [duplicate]

I am having a problem accessing the #attribute section of my SimpleXML object. When I var_dump the entire object, I get the correct output, and when I var_dump the rest of the object (the nested tags), I get the correct output, but when I follow the docs and var_dump $xml->OFFICE->{'#attributes'}, I get an empty object, despite the fact that the first var_dump clearly shows that there are attributes to output.
Anyone know what I am doing wrong here/how I can make this work?
Try this
$xml->attributes()->Token
You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.
More info at php.net
http://php.net/simplexmlelement.attributes
Example code from that page:
$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
I used before so many times for getting #attributes like below and it was a little bit longer.
$att = $xml->attributes();
echo $att['field'];
It should be more easy and you can get attributes following format only at once:
Standard Way - Array-Access Attributes (AAA)
$xml['field'];
Other alternatives are:
Right & Quick Format
$xml->attributes()->{'field'};
Wrong Formats
$xml->attributes()->field;
$xml->{"#attributes"}->field;
$xml->attributes('field');
$xml->attributes()['field'];
$xml->attributes->['field'];
$xml = <<<XML
<root>
<elem attrib="value" />
</root>
XML;
$sxml = simplexml_load_string($xml);
$attrs = $sxml->elem->attributes();
echo $attrs["attrib"]; //or just $sxml->elem["attrib"]
Use SimpleXMLElement::attributes.
Truth is, the SimpleXMLElement get_properties handler lies big time. There's no property named "#attributes", so you can't do $sxml->elem->{"#attributes"}["attrib"].
You can just do:
echo $xml['token'];
If you're looking for a list of these attributes though, XPath will be your friend
print_r($xml->xpath('#token'));
It helped me to convert the result of simplexml_load_file($file) into a JSON Structure and decode it back:
$xml = simplexml_load_file("$token.xml");
$json = json_encode($xml);
$xml_fixed = json_decode($json);
$try1 = $xml->structure->{"#attributes"}['value'];
print_r($try1);
>> result: SimpleXMLElement Object
(
)
$try2 = $xml_fixed->structure->{"#attributes"}['value'];
print_r($try2);
>> result: stdClass Object
(
[key] => value
)
Unfortunately I have a unique build (stuck with Gentoo for the moment) of PHP 5.5, and what I found was that
$xml->tagName['attribute']
was the only solution that worked. I tried all of Bora's methods above, including the 'Right & Quick' format, and they all failed.
The fact that this is the easiest format is a plus, but didn't enjoy thinking I was insane trying all of the formats others were saying worked.
Njoy for what its worth (did I mention unique build?).
I want to extract string (just Song title and Artist name) from external xml file: https://nostalgicfm.ro/NowOnAir.xml
This form of xml:
<Schedule System="Jazler">
<Event status="happening" startTime="20:31:20" eventType="song">
<Announcement Display=""/>
<Song title="Let It Be ">
<Artist name="Beatles">
<Media runTime="265.186"/>
<Expire Time="20:35:45"/>
</Artist>
</Song>
</Event>
</Schedule>
I try this code PHP but i don't know how to extract name & title...like "Beatles - Let It Be"
<?php
$url = "https://nostalgicfm.ro/NowOnAir.xml";
$xml = simplexml_load_file($url);
print_r($xml);
?>
Result is an Oject:
SimpleXMLElement Object ( [#attributes] => Array ( [System] => Jazler ) [Event] => SimpleXMLElement Object ( [#attributes] => Array ( [status] => happening [startTime] => 20:51:21 [eventType] => song ) [Announcement] => SimpleXMLElement Object ( [#attributes] => Array ( [Display] => ) ) [Song] => SimpleXMLElement Object ( [#attributes] => Array ( [title] => If You Were A Sailboat ) [Artist] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => Katie Melua ) [Media] => SimpleXMLElement Object ( [#attributes] => Array ( [runTime] => 228.732 ) ) [Expire] => SimpleXMLElement Object ( [#attributes] => Array ( [Time] => 20:55:09 ) ) ) ) ) )
Resolved it myself:
<?php
$url = 'https://nostalgicfm.ro/NowOnAir.xml';
$xml = simplexml_load_file($url);
foreach ( $xml->Event->Song->Artist->attributes() as $tag => $value );
foreach ( $xml->Event->Song->attributes() as $tag => $value1 ) {
echo $value." - ".$value1.PHP_EOL; }
?>

php simplexml element attributes specific value [duplicate]

I am having a problem accessing the #attribute section of my SimpleXML object. When I var_dump the entire object, I get the correct output, and when I var_dump the rest of the object (the nested tags), I get the correct output, but when I follow the docs and var_dump $xml->OFFICE->{'#attributes'}, I get an empty object, despite the fact that the first var_dump clearly shows that there are attributes to output.
Anyone know what I am doing wrong here/how I can make this work?
Try this
$xml->attributes()->Token
You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.
More info at php.net
http://php.net/simplexmlelement.attributes
Example code from that page:
$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
I used before so many times for getting #attributes like below and it was a little bit longer.
$att = $xml->attributes();
echo $att['field'];
It should be more easy and you can get attributes following format only at once:
Standard Way - Array-Access Attributes (AAA)
$xml['field'];
Other alternatives are:
Right & Quick Format
$xml->attributes()->{'field'};
Wrong Formats
$xml->attributes()->field;
$xml->{"#attributes"}->field;
$xml->attributes('field');
$xml->attributes()['field'];
$xml->attributes->['field'];
$xml = <<<XML
<root>
<elem attrib="value" />
</root>
XML;
$sxml = simplexml_load_string($xml);
$attrs = $sxml->elem->attributes();
echo $attrs["attrib"]; //or just $sxml->elem["attrib"]
Use SimpleXMLElement::attributes.
Truth is, the SimpleXMLElement get_properties handler lies big time. There's no property named "#attributes", so you can't do $sxml->elem->{"#attributes"}["attrib"].
You can just do:
echo $xml['token'];
If you're looking for a list of these attributes though, XPath will be your friend
print_r($xml->xpath('#token'));
It helped me to convert the result of simplexml_load_file($file) into a JSON Structure and decode it back:
$xml = simplexml_load_file("$token.xml");
$json = json_encode($xml);
$xml_fixed = json_decode($json);
$try1 = $xml->structure->{"#attributes"}['value'];
print_r($try1);
>> result: SimpleXMLElement Object
(
)
$try2 = $xml_fixed->structure->{"#attributes"}['value'];
print_r($try2);
>> result: stdClass Object
(
[key] => value
)
Unfortunately I have a unique build (stuck with Gentoo for the moment) of PHP 5.5, and what I found was that
$xml->tagName['attribute']
was the only solution that worked. I tried all of Bora's methods above, including the 'Right & Quick' format, and they all failed.
The fact that this is the easiest format is a plus, but didn't enjoy thinking I was insane trying all of the formats others were saying worked.
Njoy for what its worth (did I mention unique build?).
I want to extract string (just Song title and Artist name) from external xml file: https://nostalgicfm.ro/NowOnAir.xml
This form of xml:
<Schedule System="Jazler">
<Event status="happening" startTime="20:31:20" eventType="song">
<Announcement Display=""/>
<Song title="Let It Be ">
<Artist name="Beatles">
<Media runTime="265.186"/>
<Expire Time="20:35:45"/>
</Artist>
</Song>
</Event>
</Schedule>
I try this code PHP but i don't know how to extract name & title...like "Beatles - Let It Be"
<?php
$url = "https://nostalgicfm.ro/NowOnAir.xml";
$xml = simplexml_load_file($url);
print_r($xml);
?>
Result is an Oject:
SimpleXMLElement Object ( [#attributes] => Array ( [System] => Jazler ) [Event] => SimpleXMLElement Object ( [#attributes] => Array ( [status] => happening [startTime] => 20:51:21 [eventType] => song ) [Announcement] => SimpleXMLElement Object ( [#attributes] => Array ( [Display] => ) ) [Song] => SimpleXMLElement Object ( [#attributes] => Array ( [title] => If You Were A Sailboat ) [Artist] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => Katie Melua ) [Media] => SimpleXMLElement Object ( [#attributes] => Array ( [runTime] => 228.732 ) ) [Expire] => SimpleXMLElement Object ( [#attributes] => Array ( [Time] => 20:55:09 ) ) ) ) ) )
Resolved it myself:
<?php
$url = 'https://nostalgicfm.ro/NowOnAir.xml';
$xml = simplexml_load_file($url);
foreach ( $xml->Event->Song->Artist->attributes() as $tag => $value );
foreach ( $xml->Event->Song->attributes() as $tag => $value1 ) {
echo $value." - ".$value1.PHP_EOL; }
?>

PHP object starts with # [duplicate]

I am having a problem accessing the #attribute section of my SimpleXML object. When I var_dump the entire object, I get the correct output, and when I var_dump the rest of the object (the nested tags), I get the correct output, but when I follow the docs and var_dump $xml->OFFICE->{'#attributes'}, I get an empty object, despite the fact that the first var_dump clearly shows that there are attributes to output.
Anyone know what I am doing wrong here/how I can make this work?
Try this
$xml->attributes()->Token
You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.
More info at php.net
http://php.net/simplexmlelement.attributes
Example code from that page:
$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
I used before so many times for getting #attributes like below and it was a little bit longer.
$att = $xml->attributes();
echo $att['field'];
It should be more easy and you can get attributes following format only at once:
Standard Way - Array-Access Attributes (AAA)
$xml['field'];
Other alternatives are:
Right & Quick Format
$xml->attributes()->{'field'};
Wrong Formats
$xml->attributes()->field;
$xml->{"#attributes"}->field;
$xml->attributes('field');
$xml->attributes()['field'];
$xml->attributes->['field'];
$xml = <<<XML
<root>
<elem attrib="value" />
</root>
XML;
$sxml = simplexml_load_string($xml);
$attrs = $sxml->elem->attributes();
echo $attrs["attrib"]; //or just $sxml->elem["attrib"]
Use SimpleXMLElement::attributes.
Truth is, the SimpleXMLElement get_properties handler lies big time. There's no property named "#attributes", so you can't do $sxml->elem->{"#attributes"}["attrib"].
You can just do:
echo $xml['token'];
If you're looking for a list of these attributes though, XPath will be your friend
print_r($xml->xpath('#token'));
It helped me to convert the result of simplexml_load_file($file) into a JSON Structure and decode it back:
$xml = simplexml_load_file("$token.xml");
$json = json_encode($xml);
$xml_fixed = json_decode($json);
$try1 = $xml->structure->{"#attributes"}['value'];
print_r($try1);
>> result: SimpleXMLElement Object
(
)
$try2 = $xml_fixed->structure->{"#attributes"}['value'];
print_r($try2);
>> result: stdClass Object
(
[key] => value
)
Unfortunately I have a unique build (stuck with Gentoo for the moment) of PHP 5.5, and what I found was that
$xml->tagName['attribute']
was the only solution that worked. I tried all of Bora's methods above, including the 'Right & Quick' format, and they all failed.
The fact that this is the easiest format is a plus, but didn't enjoy thinking I was insane trying all of the formats others were saying worked.
Njoy for what its worth (did I mention unique build?).
I want to extract string (just Song title and Artist name) from external xml file: https://nostalgicfm.ro/NowOnAir.xml
This form of xml:
<Schedule System="Jazler">
<Event status="happening" startTime="20:31:20" eventType="song">
<Announcement Display=""/>
<Song title="Let It Be ">
<Artist name="Beatles">
<Media runTime="265.186"/>
<Expire Time="20:35:45"/>
</Artist>
</Song>
</Event>
</Schedule>
I try this code PHP but i don't know how to extract name & title...like "Beatles - Let It Be"
<?php
$url = "https://nostalgicfm.ro/NowOnAir.xml";
$xml = simplexml_load_file($url);
print_r($xml);
?>
Result is an Oject:
SimpleXMLElement Object ( [#attributes] => Array ( [System] => Jazler ) [Event] => SimpleXMLElement Object ( [#attributes] => Array ( [status] => happening [startTime] => 20:51:21 [eventType] => song ) [Announcement] => SimpleXMLElement Object ( [#attributes] => Array ( [Display] => ) ) [Song] => SimpleXMLElement Object ( [#attributes] => Array ( [title] => If You Were A Sailboat ) [Artist] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => Katie Melua ) [Media] => SimpleXMLElement Object ( [#attributes] => Array ( [runTime] => 228.732 ) ) [Expire] => SimpleXMLElement Object ( [#attributes] => Array ( [Time] => 20:55:09 ) ) ) ) ) )
Resolved it myself:
<?php
$url = 'https://nostalgicfm.ro/NowOnAir.xml';
$xml = simplexml_load_file($url);
foreach ( $xml->Event->Song->Artist->attributes() as $tag => $value );
foreach ( $xml->Event->Song->attributes() as $tag => $value1 ) {
echo $value." - ".$value1.PHP_EOL; }
?>

Reading XML file - strange PHP object notation

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.

PHP - get values from xml

I have a some problem with get value from xml.
XML look like
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="http://crd.gov.pl/xml/schematy/UPO/2008/05/09/UPO.xsl"?>
<pos:Document xmlns:pos="SOMEURL"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<pos:DescribeDoc/>
<pos:UPD>
<pos:IdDoc>procotol-UPD2198338</pos:IdDoc>
<pos:IdCases>221872</pos:IdCases>
<pos:additionalInfo TypeInfo="Source">Some string</pos:additionalInfo>
</pos:UPD>
...
I general try to get to pos:IdCases.
I try this code:
$domContent = new SimpleXMLElement(((string) $content), LIBXML_COMPACT);
$test = $domContent->xpath('/pos:Document/pos:UPD/*');
foreach($test as $node){
print_r($node)
}
I get a some object such as
SimpleXMLElement Object
(
[0] => procotol-UPD2198338
)
SimpleXMLElement Object
(
[0] => 221872
)
SimpleXMLElement Object
(
[#attributes] => Array
(
[TypeInfo] => Source
)
[0] => Some string
)
But I must get to pos:IdCases. I can't use index [1] because order can change.
My question is:
How can I get to value in node: pos:IdCases
I can't add id or another info to node because this xml was signed (XADES).
Can you give me some advice? Thanks for help
Simply change the XPath to match the <Pos:IdCases/> node:
$test = $domContent->xpath('/pos:Document/pos:UPD/pos:IdCases');

Categories