使用php解析XML数据
我试图从 xml 文件中的单个元素中提取文本,我能够提取整个文件,但我实际上只需要文件中的几行...
在此页面上,我能够提取整个 xml 文件( http://smyrnainlet.com/testing.php )
但是当我尝试只挑出一行时从该文件。 http://smyrnainlet.com/current_data.php
这是我收到的错误:
致命错误:调用到第 9 行 /home/content/74/8620474/html/current_data.php 中非对象上的成员函数 getbyElementID()
如果有人可以帮助我,那就太棒了,我一直在为此苦苦挣扎了几个小时。
这是我的代码:
<?php
function startElemHandler($parser, $name, $attribs)
{
if (strcasecmp($name, "current_observation") ==0 ) {
echo "<div id='waves'>\n";
}
if (strcasecmp($name, "wave_height_ft") ==0) {
$waveHeight->getbyElementID("wave_height_ft");
echo $waveHeight->asXML();
}
}
function endElemHandler($parser, $name)
{
if (strcasecmp($name, "current_observation") ==0 ) {
echo "</div>";
}
}
$parser = xml_parser_create();
xml_set_element_handler($parser, startElemHandler, endElemHandler);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
$strXML = implode("",file("http://www.weather.gov/xml/current_obs/41009.xml"));
xml_parse($parser, $strXML);
xml_parser_free($parser);
?>
I am trying to pull text from a single element in an xml file, i was able to pull the entire file but i really only need a couple of lines from the file...
On this page i was able to pull the entire xml file ( http://smyrnainlet.com/testing.php )
But when i try to just single out one line from that file.
http://smyrnainlet.com/current_data.php
This is the error i am receiving:
Fatal error: Call to a member function getbyElementID() on a non-object in /home/content/74/8620474/html/current_data.php on line 9
If anyone could help me that would be amazing, i have been struggling with this for hours.
This is my code:
<?php
function startElemHandler($parser, $name, $attribs)
{
if (strcasecmp($name, "current_observation") ==0 ) {
echo "<div id='waves'>\n";
}
if (strcasecmp($name, "wave_height_ft") ==0) {
$waveHeight->getbyElementID("wave_height_ft");
echo $waveHeight->asXML();
}
}
function endElemHandler($parser, $name)
{
if (strcasecmp($name, "current_observation") ==0 ) {
echo "</div>";
}
}
$parser = xml_parser_create();
xml_set_element_handler($parser, startElemHandler, endElemHandler);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
$strXML = implode("",file("http://www.weather.gov/xml/current_obs/41009.xml"));
xml_parse($parser, $strXML);
xml_parser_free($parser);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码存在一些基本缺陷,但您本质上是在问如何解析 XML 文件。我建议使用 PHP 的
DOMDocument
和DOMXPath
提取您需要的数据。这是一些示例代码:You have a few fundamental flaws with your code but you are essentially asking how to parse an XML file. I suggest using PHP's
DOMDocument
withDOMXPath
to extract the data you need. Here is some example code:当您尝试使用 $waveHeight 时,它似乎未定义(不在范围内)!
您可以
$waveHeight seem not defined (not in scope) wher you try to use it!
you can