总的PHP noob,但需要做一些肮脏的事情,不幸的是。。。昨天
我有一个远程网页,我可以提取,它有它的节点结构:
--html
--head
--body
--div
--section id="options"
--section id="video"
--nav id="nav"
// EVERYTHING IN THIS SECTION
--section id="inventory"
--article class="item"
--div class="info"
--div class="inner"
--div class="right"
--span class="price-label"
--span class="price"
--div class="left"
--a href="http://link-to-details-page.html"
--div class="center"
--h2 class="product-title"
--ul class="product-details"
--li
--span title="title1"
--span title="title2"
...............
--div class="clearfix"
--article class="item"
--div class="info"
...............
--div class="clearfix"
...............
...............
// END OF SECTION
--footer
我是一名程序员,但对php还是个新手。
我走了这么远。。。。
<?php
$url='http://www.example.com/inventory.html';
$homePage=file_get_contents($url);
$dom = new DOMDocument();
@$dom->loadHTML($homePage);
$xpath = new DOMXpath($dom);
$elements = $xpath->query("/html/body");
// would like to filter this more and parse results to json file
//$file = fopen( 'data.json', 'w' );
//fwrite($file, $homePage);
//fclose($fp);
echo htmlspecialchars($homePage);
?>
我的数据字符串已经在$homePage中,什么是最有效的方法
- 仅捕获部分[id="inventory"]
- 循环浏览其文章集
- 从每一篇文章中删除div.clearfix节点
- 然后将剩下的html字符串解析为JSON对象
非常感谢,如果你能帮忙的话。
更新:
或者,如果您可以向我展示如何只获取[id=inventory]部分并将其传递给javaScript函数,我就可以从那里处理它。
已解决
对于其他在这方面挣扎的人。。。。
getHtml.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>
</head>
<body>
<div id="dom-target" style="display: none;">
<?php
$url='http://www.example.com/inventory.html';
$content = file_get_contents($url);
$first_step = explode( '<section id="Inventory">' , $content );
$second_step = explode("</section>" , $first_step[1] );
$result = $second_step[0];
$result = trim(preg_replace('/'t+/', '', $result));
echo htmlspecialchars($result);
?>
</div>
<div id="result"></div> <!-- response back is posted here success/fail -->
<script>
$(document).ready(loadContent);
function loadContent() {
var div = document.getElementById("dom-target");
var result = (div.textContent);
// do your code to convert string to json
// i am leaving that part out in the solution
phpSave2File(result);
}
function phpSave2File(result) {
$.ajax({
type: "POST",
url: "/saveJson.php",
data: {data: result},
success: function(res) {
$('#result').html(res);
console.log(res);
},
error: function(err) {
console.log(err.message);
}
});
return false;
}
</script>
</body>
</html>
saveJson.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="saved-results" style="display: block;">
<?php
$post_data=$_REQUEST["data"];
if( $post_data )
{
$myfile = fopen("currInventory.txt", "w") or die("Unable to open file!");
fwrite($myfile, $post_data);
fclose($myfile);
echo $post_data;
} else {
die('no post data to process');
}
?>
</div>
</body>
</html>