解析内容仅存储一个结果

问题描述 投票:0回答:1

我有一些问题让我非常凌乱的代码正确地提交数据。目前我正在抓取一个网站,其中包含许多图像并试图收集它们并通过我的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数据的部分正在我们的初始解析循环内部加载,但是在收集图像+视频的循环之外。

php wordpress simple-html-dom
1个回答
3
投票

每次循环你只需收集一条信息并将$thecontent设置到该字段并打印出来。您需要将这些添加到一起以获取包含所有内容的字符串...

$thecontent = '';
foreach ($html2->find('.entry-content img') as $image) {
    $imageurl  = $image->src;
    $new = '<img src="' . $imageurl . '" style="height: auto; width: 100%;margin-bottom: 3px;">';
    $thecontent .= htmlspecialchars($new).'<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>';
    $thecontent .= htmlspecialchars($new).'<br>';
}
print $thecontent;

注意在每个循环中我使用.=将新内容附加到列表的末尾。打印出最终内容,应该使用

© www.soinside.com 2019 - 2024. All rights reserved.