【发布时间】:2018-01-13 07:54:52
【问题描述】:
我在让极其混乱的代码正确提交数据时遇到了一些问题。目前,我正在抓取一个包含许多图像的网站,并尝试通过我的 WordPress the_content 选择将它们全部收集并相应地存储它们。
这是我到目前为止所做的事情,当我通过标准循环加载图像时,它几乎没有任何问题地返回图像。
foreach ($html2->find('.entry-content img') as $image) {
$imageurl = $image->src;
$new = '<img src="' . $imageurl . '" style="height: auto; width: 100%;margin-bottom: 3px;">';
print $thecontent = htmlspecialchars($new); print '<br>';
} foreach ($html2->find('iframe') as $video) {
$videourl = $video->src;;
$new = '<iframe src="' . $videourl . '" scrolling="no" frameborder="0" width="100%" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>';
print $thecontent = htmlspecialchars($new); print '<br>';
}
上面的代码将返回如下所示的内容,其中包含 1 - 我们尝试收集多少图像 + 视频。
<img src="https://www.example.com/some-image-path-here.jpg" style="height: auto; width: 100%;margin-bottom: 3px;">
<img src="https://www.example.com/some-image-path-here.jpg" style="height: auto; width: 100%;margin-bottom: 3px;">
<img src="https://www.example.com/some-image-path-here.jpg" style="height: auto; width: 100%;margin-bottom: 3px;">
<img src="https://www.example.com/some-image-path-here.jpg" style="height: auto; width: 100%;margin-bottom: 3px;">
现在这是我用来尝试将内容上传到我的 WordPress 网站的内容(除了$content 之外的所有内容似乎都正常工作。
$content = $thecontent;
$my_post = array(
'post_title' => wp_strip_all_tags( trim( $title ) ),
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 2,
'post_category' => array(2),
'post_date' => date('Y-m-d H:i:s')
);
$post_id = wp_insert_post( $my_post );
remove_filter('content_save_pre', 'wp_filter_post_kses');
remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
上面的代码在我的 WordPress the_content 部分返回以下内容,这只是第一张图片,我怎样才能使它工作?
<img src="https://www.example.com/some-image-path-here.jpg" style="height: auto; width: 100%;margin-bottom: 3px;">
注意:存储 WordPress 数据的部分在我们的初始解析循环内加载,但在收集图像+视频的循环之外。
【问题讨论】:
-
您在循环中的每次迭代中覆盖您的变量(完全替换内容)而不是连接它们,这意味着您的变量将只包含 last 元素。
标签: php wordpress simple-html-dom