SimpleXML 将标签内容保存为变量

发布于 2024-11-17 05:21:39 字数 191 浏览 3 评论 0原文

好的,到目前为止我一直在使用标签属性,但是如果我想将标签的实际内容保存为变量,我该怎么做?

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

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

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

盛夏尉蓝 2024-11-24 05:21:39

您是在谈论 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 将具有不同的根元素,可能包含多个 元素,然后您可以通过数组表示法获得这些元素,如 ;

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

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

$john = $xml->xpath('人/名字');

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

慈悲佛祖 2024-11-24 05:21:39

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

更多信息可在 此处获取

希望有帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文