SimpleXML将标记内容保存为变量

时间:2011-06-27 23:28:58

标签: variables tags simplexml

好的我到目前为止一直在处理标记属性,但是如果我想将标记的实际内容保存为变量怎么办呢?

例如,在下面的示例中,如何将“John”保存到变量?

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

谢谢!

2 个答案:

答案 0 :(得分:1)

您在谈论PHP中的SimpleXML?

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?><person><name>John</name></person>'); 
$john = $xml->name ;
echo $john ;

我们在示例而不是$xml->name中使用$xml->person->name的原因是SimpleXML将假设根元素(值得记住:)。在一个真实的例子中,XML将有一个不同的根元素,可能有几个<person>元素,然后您可以通过数组表示法获得,如;

$james = $xml->person[4]->name ;

更强大的方法是使用Xpath,这是值得研究的,以便更好地处理复杂的XML;

$ john = $ xml-&gt; xpath('person / name');

答案 1 :(得分:1)

使用PHP,您可以这样做: -

<?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.
 */
?>

有更多信息here

希望它有所帮助。