如何使用foreach()来迭代YQL XML和抓取HTML


How to use foreach() to iterate YQL XML and scrape HTML?

我不知道该怎么称呼它,所以我将快速阐述一下。

我有一个屏幕刮板,我试图建立,使用YQL控制台。查询为用户提供XML或JSON的选择。我的目标是控制台的YQL>data>html方面,并选择XML作为输出格式。

My YQL Query:

SELECT * FROM html WHERE url="http://google.com"

这将为您提供一个XML格式的Google.com文档树的读数。太多的输出粘贴到这篇文章,所以直接点击链接。

我的问题是用PHP遍历XML树以正确显示该请求的输出。我不知道如何有效地创建foreach语句(或任何其他语句)来有效地抓取XML输出和收集Document树,并根据自己的需要重新显示它。

我的PHP:

$searchUrl = "google.com";
if(isset($_REQUEST['searchUrl'])) {
    $searchUrl = $_REQUEST['searchUrl'];
}
$query = "select * from html where url='"http://".$searchUrl."'"";
$url = "http://query.yahooapis.com/v1/public/yql";
// Get Subcategory Article Data
$parameterData = "q=".urlencode($query);
$parameterData .= "&diagnostics=true";
// setup CURL 
$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameterData); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
// send
$response = trim(urldecode(curl_exec($ch)));
// parse response
$xmlObjects = @simplexml_load_string($response);
foreach ($xmlObjects->diagnostics as $diagnostics) {
    echo "<a href=".$diagnostics->url." target='_blank'>".$diagnostics->url."</a>";
}
foreach ($xmlObjects->results as $result) {
    // here is where I would go echo $result->body or something along those lines
}

我想我在这一点上有点难住了,因为我缺乏知识,不知道下一步该在这种格式的XML树中导航。在XML中的query>results>body之后,我不确定在哪里收集剩余的对象,并将其输出到我的文档中的pre标记或该性质的东西。

我想为用户提供一个输入字段来输入他们自己的域,我的PHP将提交查询,遍历响应,并将Document树返回给用户以进行HTML查看和调试。

我熟悉PHP和XML在迭代大量具有相同内部结构的父元素的上下文中,如RSS提要或类似性质的东西。在本例中,我处理的是一个动态XML树,其中包含一个大型响应对象和一个波动的内部结构。

下面的代码将结果体显示为html页面:

<?php
 // ... the code you posted in the question
 //     !without the diagnostics output!
 //     read comments of the answer to know why
?>
<html>
  <head>
  </head>
<?php
foreach ($xmlObjects->results as $result) {
    // asXml() will return the content of body as xml string
    echo $result->body->asXml();
    break;
}
?>
</html>

请注意,由于您不会通过YQL获得页面的<head>元素,因此在大多数情况下输出将看起来很混乱。