Reputation: 987
OK I've been working with tag attributes up to now, but what if I want to save the actual contents of a tag as a variable, how would I do that?
For instance, in the example below, how would I save 'John' to a variable?
<person>
<name>John</name>
</person>
Thanks!
Upvotes: 0
Views: 393
Reputation: 7995
Using PHP, you can do it in this way:-
<?php
$xmlstr = <<<XML
<person>
<name>John</name>
</person>
XML;
$xml = new SimpleXMLElement($xmlstr);
$name_person = $xml->name;
// If you are unsure about the node string, then it's best to write it as:-
$name_person = $xml->{'name'};
/**
* This above statement will take care if the node string contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.
*/
?>
More info is available here.
Hope it helps.
Upvotes: 1
Reputation: 2028
You're talking about SimpleXML in PHP?
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?><person><name>John</name></person>');
$john = $xml->name ;
echo $john ;
The reason we use $xml->name
in our example rather than $xml->person->name
is that SimpleXML will assume the root element (worth keeping in mind :). In a real example the XML would have a different root element, with perhaps several <person>
elements, which you then could get by array notation, as in ;
$james = $xml->person[4]->name ;
A more powerful way is to use Xpath which is worth looking into for better dealing with complex XML ;
$john = $xml->xpath ( 'person/name' ) ;
Upvotes: 1