在本文中,我们将学习如何使用PHP处理 XML。我们已经学习了 XML 的基础知识以及它们与 HTML 的区别。可以从 XML Elements 中学习 XML 的不同元素以了解以下程序的工作。
simplexml_load_string()函数用于解析给定的 XML,然后可以使用 XML 对象访问 XML 数据。
示例 1:以下示例读取并打印给定的 XML字符串。
HTML
GeeksForGeeks
Tom
Submission
Please see my articles of PHP!
";
/* The function reads xml data
from the passed string */
$xml = simplexml_load_string($myXMLData)
or die("Error: Cannot create xml data object");
print_r($xml);
?>
HTML
GeeksForGeeks
Get data from XML data string
GeeksForGeeks
John
Submission
Please see my articles of PHP!
";
/* The function reads xml data
from the passed string */
$xml = simplexml_load_string($myXMLData)
or die("Error: Cannot create xml data object");
echo "To : " . $xml->to . "
";
echo "From : " . $xml->from . "
";
echo "Subject : " . $xml->heading . "
";
echo "Mail : " . $xml->body;
?>
输出:
SimpleXMLElement Object
(
[to] => GeeksForGeeks
[from] => Tom
[heading] => Submission
[body] => Please see my articles of PHP!
)
示例 2:以下示例演示如何使用PHP获取 XML 节点值。节点值显示在下面给出的输出中。
HTML
GeeksForGeeks
Get data from XML data string
GeeksForGeeks
John
Submission
Please see my articles of PHP!
";
/* The function reads xml data
from the passed string */
$xml = simplexml_load_string($myXMLData)
or die("Error: Cannot create xml data object");
echo "To : " . $xml->to . "
";
echo "From : " . $xml->from . "
";
echo "Subject : " . $xml->heading . "
";
echo "Mail : " . $xml->body;
?>
输出: