开发者

SimpleXML save tag content as variable

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开发者_JS百科 'John' to a variable?

<person>
    <name>John</name>
</person>

Thanks!


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜