我已经在 PHP 中加载了一个带有“simplexml_load_file”的 XML 文件,现在我想从中读取一些元素以使用 PHP 将它们打印出来。我发现的所有方法都没有成功,因为我的 XML 文件可能太复杂了……我发现的最好的东西如下:
只是想添加一篇关于如何从 SimpleXMLElement 中提取值的帖子。它不像你想象的那么简单。因为它是一个复杂的对象,所以您不能直接访问该元素。这是表示 SimpleXmlElement 的 var_dump 的数据示例
array(1) { [0]=> object(SimpleXMLElement)#13 (2) { ["@attributes"]=> array(1) { ["name"]=> string(5) "title" } [0 ]=> string(19) "PHP 技术手册" } }
如果要提取书名,则必须将指定的元素转换为这样的字符串。$newTitle = (string) $title[0];
$title 变量是您使用 simplexml_load_string 从 xml 文档中提取的 SimpleXMLElement。要最初从 xml 文档中访问 title 元素,您可以使用 xpath 这样做。$title = $doc->xpath('str[@name="title"]');
希望这可以帮助那里的人。
我尝试使用“$title = $doc->xpath('str[@name="title"]');” 用我自己的 XML 文件将其替换为我自己的元素,但随后出现 PHP 错误:
遇到 PHP 错误严重性:通知消息:数组到字符串转换文件名:views/welcome_message.php 行号:79
这是我的代码:
<?php
if (file_exists('data.xml')) {
$xml = simplexml_load_file('data.xml');
$title = $xml->xpath('str[@name="name"]');
echo $title;
} else {
exit('Failed to open test.xml.');
}
?>
这是我非常混乱的 xml 文件的一小部分摘录:
SimpleXMLElement 对象([文件夹] => SimpleXMLElement 对象([@attributes] => 数组([名称] => ABC)[文件] => SimpleXMLElement 对象([@attributes] => 数组([名称] => DEF [大小] => 123 [创建时间] => 03.09.2012 16:36:59 [最后写入时间] => 06.09.2012 10:46:39 [id3v2] => 1 [v2-tag-PRIV] = > XMP ; WM/MediaClassSecondaryID; WM/MediaClassPrimaryID ?}`?#??K??H?*(D; WM/Provider AMG; WM/WMContentID ???E?@??B????; WM/WMCollectionID ?Yd??B??N5 ?; WM/WMCollectionGroupID ]?????N?????^e; WM/UniqueFileIdentifier AMG a _ id = R 2 0 5 6 3 8 9 ; AMG p _ id = P 2 6 4 5 ; AMG t _ id = T 2 2 1 6 6 0 0 3 [v2-track] => 2 [v2-song-title] => FGH [v2-album] => IJK [ v2-流派] => (12) [v2-tag-TPUB] => LMN [v2-tag-TYER] =>1997 [v2-tag-TPE2] => OPQ [v2-composer] => RST [v2-artist] => UVW [id3v1] => 1 [song-title] => XYZ [artist] => ARTIST1 [album- title] => TITLE1 [year] => 1997 [comment] => [track] => 2 [genre] => Other [mpeg-version] => 1 [mpeg-layer] => 3 [bitrate] => 320Kbps [采样率] => 48000Hz [通道模式] => JointStereo ) )
为什么 [@attributes] 中有一个“@”,我该如何处理?如何从不同元素中获取信息?