简体   繁体   English

使用PHP解析XML网页

[英]Parse an XML webpage using PHP

How do I use PHP to parse XML on the web? 如何使用PHP解析Web上的XML?

Here is the example XML . 这是XML示例 How would you get the value of the first "AskRealtime"? 您将如何获得第一个“ AskRealtime”的价值?

I am aware of SimpleXML. 我知道SimpleXML。 I am looking for the proper code to open the XML webpage, and work with it using SimpleXML. 我正在寻找合适的代码来打开XML网页,并使用SimpleXML对其进行处理。

This suggested code does not succesfully load the page: 此建议的代码无法成功加载页面:

$xml = @simplexml_load_file("http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20AskRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22A%22%2C%22AA%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");

$price = $xml->results->quote[0]->AskRealtime;

echo $price;

Step 1 . 步骤1 - load the file in SimpleXML $xml = @simplexml_load_file($fl) or die($errorMsg); -将文件加载到SimpleXML $xml = @simplexml_load_file($fl) or die($errorMsg); where $fl is the file URL and $errorMsg is the error message to display. 其中$ fl是文件URL,而$ errorMsg是要显示的错误消息。

Step 2 . 第二步 - get a content $whatever=$xml->results->quote->AskRealtime[0]; -获取内容$whatever=$xml->results->quote->AskRealtime[0]; Explained: it goes to the XML, then what is named "results", then what is named "quote", then what is named AskRealtime, but the first (index 0) of it. 解释:转到XML,然后是“结果”,然后是“ quote”,然后是AskRealtime,但是它的第一个(索引0)。

And a note : if, for some reason, you'll have to get something which is named whatever-else (so it has a - in the name), then it works only if you make the code $xml->{'whatever-else'} 还有一个注释 :如果由于某种原因,您必须获得一个名为what-else的东西(因此它的名称中带有-),那么只有在使代码$xml->{'whatever-else'}

Have you tried using SimpleXMLElement? 您是否尝试过使用SimpleXMLElement? It works just like your code but it's constructed differently. 它的工作方式与您的代码相同,但结构不同。

$url = 'http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20AskRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22A%22%2C%22AA%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
$xml = new SimpleXMLElement($url, null, true);
echo $xml->results->quote[0]->AskRealtime;

There are different methods for getting the file contents, even though I doubt it's the problem. 尽管我怀疑这是问题所在,但是有多种获取文件内容的方法。

/* cURL */
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($curl);
curl_close($curl);

/* Alternative */
$contents = file_get_contents($url);

Can you tell what is the error you get? 您能说出您得到的错误是什么吗? Or try var_dump($xml) and see what it returns. 或者尝试var_dump($xml)看看它返回什么。

Use can use some HTTP request library to get the file, eg: http://www.php.net/manual/en/function.http-get.php 使用可以使用一些HTTP请求库来获取文件,例如: http : //www.php.net/manual/en/function.http-get.php

Then feed the response to SimpleXML. 然后将响应输入到SimpleXML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM