使用php curl进行Web刮取
我有一个包含以下代码的html页面。现在我只想以json格式打印本地页面中的名称和位置使用php curl进行Web刮取,php,html,json,curl,web-scraping,Php,Html,Json,Curl,Web Scraping,我有一个包含以下代码的html页面。现在我只想以json格式打印本地页面中的名称和位置 <div class='post-header'> <div class='post-header-line-1'></div> </div> <div class='post-body entry-content' id='post-body-210098160524748093' itemprop='articleBody'> <div
<div class='post-header'>
<div class='post-header-line-1'></div>
</div>
<div class='post-body entry-content' id='post-body-210098160524748093' itemprop='articleBody'>
<div class="separator" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em; text-align: center;">
<br /></div>
<br />
<br />
<ul>
<li>Name<br />Location</li>
<li>Name<br />location</li>
<li>name<br />location</li>
<li>name<br />location</li>
</ul>
<br />
您可以获取
元素的内容,将它们按
拆分,然后使用jQuery生成JSON,然后使用jQueryPOST
请求方法将其传递给PHP:
$().ready(function() {
var storeLocations = new Array();
var storeName = new Array();
$("li").each(function() {
var content = $(this).text().split('<br />');
storeName[storeName.length] = content[0];
storeLocation[storeLocation.length] = content[1];
});
var jsonString = '{["contacts:["';
for(var i = 0; i < storeLocations.length; i++) {
jsonString += '{"id:' + i + ', "name:"' + storeName[i] + '", "location:"' + storeLocation[i] + '"},';
}
jsonString += "]]}";
var url = "form.php";
$.post(url, jsonString);
});
$().ready(函数()){
var storeLocations=新数组();
var storeName=新数组();
$(“li”)。每个(函数(){
var content=$(this.text().split(“
”);
storeName[storeName.length]=内容[0];
storeLocation[storeLocation.length]=内容[1];
});
var jsonString='{[”联系人:[';
对于(变量i=0;i
另一种方法是使用正则表达式
<?php
$re = '/<li>([a-zA-Z]+)<br \/>([a-zA-Z]+)<\/li>/m';
$str = '<li>Name<br />Location</li>
<li>Name<br />location</li>
<li>name<br />location</li>
<li>name<br />location</li>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
$arrayOfResults = [];
foreach($matches as $n => $match) {
$arrayOfResults["contacts"][] = [
"id" => $n + 1,
"name" => $match[1],
"location" => $match[2]
];
}
$json = json_encode($arrayOfResults);
var_dump($json);
通过curl加载页面,然后使用DOMDocument,然后在数组中收集节点值,最后使用json编码问题中不包括jquery
标记,但无论如何,不需要手动构建json字符串,只需使用json.stringify(javascript\u对象)
,如果你想要一个json字符串,或者仅仅是整个对象,那么这将是最好的选择,让PHP解码itI。我知道,我不知道如何使用PHP直接从页面中获取页面元素,所以我提出了下一个想法。谢谢你提供的信息。
<?php
$re = '/<li>([a-zA-Z]+)<br \/>([a-zA-Z]+)<\/li>/m';
$str = '<li>Name<br />Location</li>
<li>Name<br />location</li>
<li>name<br />location</li>
<li>name<br />location</li>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
$arrayOfResults = [];
foreach($matches as $n => $match) {
$arrayOfResults["contacts"][] = [
"id" => $n + 1,
"name" => $match[1],
"location" => $match[2]
];
}
$json = json_encode($arrayOfResults);
var_dump($json);