GET-PLACES-TIKTOK-FACEBOOK

Get TikTok and Facebook content of a specific place.

Refer at github for template (updated at 21 NOV 2023):

Output Screenshots

TikTok

Facebook

Implementation on Your Website

form.php

<!DOCTYPE html>
<html>
<body>
    <form method="post" action="get-places-tiktok-facebook.php">
        <label for="platform">platform:</label>
        <input type="text" name="platform" id="platform" required><br>
        <label for="mainPlace">mainPlace:</label>
        <input type="text" name="mainPlace" id="mainPlace" required><br>
        <label for="name">name:</label>
        <input type="text" name="name" id="name" required><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

A form where user can input the platform of choice ("tiktok" or "facebook"), mainPlace (e.g. "Ipoh"), and name (e.g. "10 Studio Cafe")

get-places-tiktok-facebook.php

Import

<!DOCTYPE html>
<html>
<head>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@600&display=swap" rel="stylesheet">
    <link href="get-places-tiktok-facebook.css" rel="stylesheet">
</head>
</html>

Importing Google Fonts and CSS

HTML Layout

<!DOCTYPE html>
<html>
<body>
    <div style="width:100%;height:97vh;">
        <div id="bannerForTikTok">
            <img src="tiktokLogo.png" style="max-height:150px;max-width:150px;">
        </div>
        <div id="bannerForFacebook">
            <img src="facebookLogo.png" style="max-height:150px;max-width:150px;">
        </div>
        <div id="contentSection">
            <img src='loading.gif' style="width:50px;height:50px" />
        </div>
    </div>
</body>
</html>

The main layout which consists of the banner (TikTok/Facebook), and the content section which displays the TikTok/Facebook content for a specific place.

JavaScript for building the layout

    <script>
        // Variables to store data fetched from the server
        var processedUrls;
        var videoViewsArray;
        var usernameArray;
        var likesArray;
        var titleArray;
        var tagArray;
        var tagViewsArray;
        var imageURLArray;
        var linksArray;
        var tagLinksArray;
        // Function to display a banner based on the platform
        function showBanner(platform) {
            // Check the platform and display the corresponding banner
            if (platform == "tiktok") {
                var loadingDiv = document.getElementById("bannerForTikTok");
                loadingDiv.style.display = "flex";
            } else {
                var loadingDiv = document.getElementById("bannerForFacebook");
                loadingDiv.style.display = "flex";
            }
        }
        //---------------------------------------------------------------- DISPLAY RESULT FOR FACEBOOK
        // Function to create HTML blocks for Facebook content
        function createLocationBlock() {
            var relatedVideosHTML = "";
            // Loop through processed URLs and create HTML for posts and photos
            for (var i = 0; i < processedUrls.length; i++) {
                var isPost = processedUrls[i].includes("/posts/");
                var isPhoto = processedUrls[i].includes("/photos/");
                if (isPost || isPhoto) {
                    var videoHTML = `
                    <div style="width: 100%; display: flex; justify-content: center; align-items: center; flex-wrap: wrap;">
                        <iframe src="https://www.facebook.com/plugins/post.php?href=${processedUrls[i]}&show_text=true&width=500" width="500" height="788" style="border: none; overflow: hidden; scroll: no;" frameborder="0" allowfullscreen="true" allow="autoplay;clipboard-write;encrypted-media;picture-in-picture;web-share"></iframe>
                    </div>
                    `;
                    relatedVideosHTML += videoHTML;
                }
            }
            return relatedVideosHTML;
        }
        // Function to add Facebook content blocks to the info section
        function addLocationBlocks() {
            var sectionHeadersHTML = `
            <div style='padding:15px 0px 15px 0px;text-align:center;vertical-align:center;font-weight:600;font-size:27px;font-family:Arial, sans-serif;color:#1877F2'>Related posts</div>
            <div>${createLocationBlock()}</div>
            `;
            var contentSection = document.getElementById("contentSection");
            contentSection.innerHTML = "";
            contentSection.style.display = 'block';
            contentSection.style.justifyContent = '';
            contentSection.style.alignItems = '';
            contentSection.innerHTML = sectionHeadersHTML;
        }
        //---------------------------------------------------------------- DISPLAY RESULT FOR FACEBOOK
        //---------------------------------------------------------------- DISPLAY RESULT FOR TIKTOK
        // Function to generate HTML for related TikTok videos
        function generateRelatedVideosHTML() {
            var relatedVideosHTML = "";
            // Loop through TikTok data and generate HTML for each video
            for (var i = 0; i < videoViewsArray.length; i++) {
                var videoHTML = `
                <a class='tiktokLink' target='_blank' href="${linksArray[i]}">
                    <div class='container'>
                        <div class='image-block' style='background-image:url(${imageURLArray[i]})'>
                            <div class='view-count'>▷ ${videoViewsArray[i]}</div>
                        </div>
                        <div class='main'>
                            <div class='video-title'>${titleArray[i]}</div>
                            <div class='row'>
                                <div class='username'>${usernameArray[i]}</div>
                                <div class='likes' style='margin-right:5px;margin-left:10px;color:#FF2B52'>❤</div>
                                <div class='likes'>${likesArray[i]}</div>
                            </div>
                        </div>
                    </div>
                </a>
                `;
                relatedVideosHTML += videoHTML;
            }
            return relatedVideosHTML;
        }
        // Function to generate HTML for TikTok hashtags
        function generateHashtagsHTML() {
            var hashtagsHTML = "";
            // Loop through TikTok hashtag data and generate HTML for each hashtag
            for (var i = 0; i < tagArray.length; i++) {
                var hashtagHTML = `
                <a class='tiktokLink' href="${tagLinksArray[i]}" target='_blank'>
                    <div class='hashtag-block'>
                        <div class='hashtag-content'>
                            <span class='hashtag-text'>${tagArray[i]}</span>
                            <div style='margin-top: 5px; font-size: 15px;'>${tagViewsArray[i]}</div>
                        </div>
                    </div>
                </a>
                `;
                hashtagsHTML += hashtagHTML;
            }
            return hashtagsHTML;
        }
        // Function to generate HTML for TikTok section headers
        function generateSectionHeaders() {
            var sectionHeadersHTML = `
            <div class='sectionHeader'>Related videos</div>
            <div class='container-wrapper'>${generateRelatedVideosHTML()}</div>
            <div class='sectionHeader'>Hashtags</div>
            <div class='container-wrapper'>${generateHashtagsHTML()}</div>
            `;
            var contentSection = document.getElementById("contentSection");
            contentSection.innerHTML = "";
            contentSection.style.display = 'block';
            contentSection.style.justifyContent = '';
            contentSection.style.alignItems = '';
            contentSection.innerHTML = sectionHeadersHTML;
        }
        // Function to display a no-result message for TikTok
        function noResult() {
            var sectionHeadersHTML = `
            <img src='noResult.png' style="width:200px;height:240px"/>
            `;
            var contentSection = document.getElementById("contentSection");
            contentSection.innerHTML = "";
            contentSection.innerHTML = sectionHeadersHTML;
        }
        //---------------------------------------------------------------- DISPLAY RESULT FOR TIKTOK
    </script>

Responsible for building the layout after the content is retrieved.

PHP cording for streams to TikTok or Facebook content

// Get the "platform" value from the POST data
$platform = $_POST["platform"];
// Display a banner based on the platform using JavaScript
if ($platform == "tiktok") {
    echo "<script>showBanner('" . $platform . "');</script>";
} else {
    echo "<script>showBanner('" . $platform . "');</script>";
}
// Flush the output buffer to ensure immediate output to the browser
ob_flush();
flush();
// Get additional POST data
$mainPlace = $_POST["mainPlace"];
$name = $_POST["name"];
// URL encode the name and main place
$encodedName = urlencode($name);
$encodemainPlace = urlencode($mainPlace);
// Get the "platform" value again from the POST data
$platform = $_POST["platform"];
// Process based on the platform ("tiktok" or "facebook")
if ($platform == "tiktok") {
    // Construct the search text for TikTok
    $encodedsearchText = $encodedName . "+" . $encodemainPlace . "+tiktok";
    // Create a Google search URL for TikTok
    $googleURL = "https://www.google.com/search?q=" . $encodedsearchText . "";
    // Array to store TikTok URLs
    $urlArray = array();
    // Fetch content from the Google search page
    $a = file_get_contents($googleURL);
    // Create a DOMDocument to parse the HTML content
    $dom = new DOMDocument();
    // Enable internal error handling
    libxml_use_internal_errors(true);
    // Load HTML content into the DOMDocument
    $dom->loadHTML($a);
    // Disable internal error handling
    libxml_use_internal_errors(false);
    // Create an XPath instance
    $xpath = new DOMXPath($dom);
    // Query anchor tags with TikTok discover URLs
    $anchorTags = $xpath->query("//a[contains(@href, 'https://www.tiktok.com/discover/')]");
    // Iterate through the anchor tags
    foreach ($anchorTags as $anchor) {
        // Get the href attribute value
        $href = $anchor->getAttribute('href');
        // Check if it is a TikTok discover URL
        if (strpos($href, '/url?q=https://www.tiktok.com/discover/') === 0) {
            // Clean and decode the URL, then add it to the array
            $cleanUrl = urldecode(substr($href, 7));
            $cleanUrl = explode("&sa", $cleanUrl)[0];
            $urlArray[] = $cleanUrl;
        }
    }
    // Check if the URL array is empty
    if (empty($urlArray)) {
        // Display a JavaScript function call if there are no TikTok results
        echo "<script>tiktokNoResult();</script>";
    } else {
        // Call the forTikTok function with the first URL from the array
        forTikTok($urlArray[0]);
    }
} elseif ($platform == "facebook") {
    // Construct the search text for Facebook
    $testing = $encodedName . "+" . $encodemainPlace . "+facebook";
    // Call the forFacebook function with the constructed search text
    forFacebook($testing);
}
  1. Retrieve Platform Value from POST Data:

    • Obtain the "platform" value from the POST data using $_POST["platform"].

  2. Display Banner Based on Platform:

    • Use an if-else statement to determine the platform.

    • If the platform is "tiktok," display a JavaScript banner using showBanner('tiktok').

    • If the platform is not "tiktok," display a JavaScript banner with the actual platform value.

  3. Flush Output Buffer:

    • Flush the output buffer to ensure immediate display of content in the browser.

  4. Retrieve Additional POST Data:

    • Get additional POST data such as "mainPlace" and "name" using $_POST["mainPlace"] and $_POST["name"].

  5. URL Encode Name and Main Place:

    • Encode the "name" and "mainPlace" variables using urlencode().

  6. Retrieve Platform Value Again:

    • Reassign the "platform" variable with the value from the POST data.

  7. Process Based on Platform:

    • If the platform is "tiktok":

      • Construct a search text for TikTok by concatenating encoded name, encoded main place, and "tiktok."

      • Create a Google search URL using the constructed search text.

      • Fetch content from the Google search page using file_get_contents().

      • Parse the HTML content using a DOMDocument and XPath.

      • Extract TikTok discover URLs from anchor tags and store them in an array.

      • If the array is empty, display a JavaScript function call for no TikTok results.

      • Otherwise, call the forTikTok function with the first URL from the array.

    • If the platform is "facebook":

      • Construct a search text for Facebook by concatenating encoded name, encoded main place, and "facebook."

      • Call the forFacebook function with the constructed search text.

PHP for TikTok content

function forTikTok($url)
{
    // Fetch the content of the TikTok page using the provided URL
    $a = file_get_contents($url);
    // Arrays to store various data extracted from the TikTok page
    $videoViewsArray = array();
    $usernameArray = array();
    $likesArray = array();
    $titleArray = array();
    $tagArray = array();
    $tagViewsArray = array();
    $imageURLArray = array();
    $linksArray = array();
    $tagLinksArray = array();
    $somethingWong = false; // Flag to check if something went wrong during extraction
    // FILTERING LINKS
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($a);
    libxml_use_internal_errors(false);
    $xpath = new DOMXPath($dom);
    // XPath query to find specific <div> elements with the class, tiktok-1as5cen-DivWrapper e1cg0wnj1
    $divClass = "tiktok-1as5cen-DivWrapper e1cg0wnj1";
    $divQuery = "//div[contains(@class, '$divClass')]";
    $targetDivs = $xpath->query($divQuery);
    foreach ($targetDivs as $targetDiv) {
        // Extract author anchors and construct complete URLs
        $authorAnchors = $xpath->query(".//a", $targetDiv);
        foreach ($authorAnchors as $anchor) {
            $href = $anchor->getAttribute('href');
            $linksArray[] = "https://www.tiktok.com" . $href;
        }
    }
    //FILTERING VIDEO VIEWS
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($a);
    libxml_use_internal_errors(false);
    $xpath = new DOMXPath($dom);
    // XPath query to find specific <strong> elements which are inside a div with the class, tiktok-k7smtc-DivCoverFooter e1aajktk7
    $strongElements = $xpath->query("//div[contains(@class, 'tiktok-k7smtc-DivCoverFooter e1aajktk7')]/strong");
    foreach ($strongElements as $strong) {
        // Extract the text content which is inside the <strong> element
        $likesCount = $strong->nodeValue;
        $videoViewsArray[] = $likesCount;
        $linksArray[] = "https://www.tiktok.com";
    }
    //FILTERING USERNAMES
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($a);
    libxml_use_internal_errors(false);
    $xpath = new DOMXPath($dom);
    // XPath query to find specific <p> elements with the class, tiktok-18g0m3y-PInfo-StyledH3UniqueId e1aajktk12
    $usernames = $xpath->query("//p[contains(@class, 'tiktok-18g0m3y-PInfo-StyledH3UniqueId e1aajktk12')]");
    foreach ($usernames as $p) {
        // Extract the text content which is inside the <p> element
        $username = $p->nodeValue;
        $usernameArray[] = $username;
    }
    //FILTERING LIKES
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($a);
    libxml_use_internal_errors(false);
    $xpath = new DOMXPath($dom);
    // XPath query to find specific <span> elements with the class, tiktok-1cgeagm-SpanLikes e1aajktk13
    $likesSpans = $xpath->query("//span[contains(@class, 'tiktok-1cgeagm-SpanLikes e1aajktk13')]");
    foreach ($likesSpans as $span) {
        // Extract the text content which is inside the <span> element
        $likesCount = $span->nodeValue;
        $likesArray[] = $likesCount;
    }
    //FILTER TITLE
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($a);
    libxml_use_internal_errors(false);
    $xpath = new DOMXPath($dom);
    // XPath query to find specific <div> elements with the class, tiktok-156kx37-DivVideoDescription e1aajktk10
    $fruitDivs = $xpath->query("//div[contains(@class, 'tiktok-156kx37-DivVideoDescription e1aajktk10')]");
    foreach ($fruitDivs as $div) {
        // Extract the text content from the 'title' attribute of the <div>
        $titleArray[] = $div->getAttribute('title');
    }
    //FILTERING TAGS AND VIEWS
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($a);
    libxml_use_internal_errors(false);
    $xpath = new DOMXPath($dom);
    // XPath query to find specific <div> elements with the class, tiktok-1s2ovfk-DivContent eabhyw07 and contains the word 'views'
    $targetDivs = $xpath->query('//div[contains(@class, "tiktok-1s2ovfk-DivContent eabhyw07")][contains(., "views")]');
    foreach ($targetDivs as $targetDiv) {
        $h4Element = $xpath->query('.//h4', $targetDiv)->item(0);
        $h4Content = $h4Element ? $h4Element->textContent : "";
        $divElement = $xpath->query('.//div', $targetDiv)->item(0);
        $divContent = $divElement ? $divElement->textContent : "";
        $tagArray[] = "#" . $h4Content;
        $tagLinksArray[] = "https://www.tiktok.com/tag/" . $h4Content;
        $tagViewsArray[] = $divContent;
    }
    if ($targetDivs->length === 0) {
        $somethingWong = true;
    }
    //FILTERING IMAGES 
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($a);
    libxml_use_internal_errors(false);
    $xpath = new DOMXPath($dom);
    // XPath query to find specific <div> elements with the class, tiktok-1jxhpnd-DivContainer e1yey0rl0
    $divElements = $xpath->query("//div[contains(@class, 'tiktok-1jxhpnd-DivContainer e1yey0rl0')]");
    foreach ($divElements as $div) {
        // Extract image tags and get its source link
        $imgElements = $xpath->query(".//img", $div);
        foreach ($imgElements as $img) {
            $imageURLArray[] = $img->getAttribute("src");
        }
    }
    // Check if there is an issue during tag and view extraction
    if ($somethingWong) {
        echo "<script>noResult();</script>";
    } else {
        // If extraction is successful, convert arrays to JavaScript variables
        echo "
            <script>
                videoViewsArray = " . json_encode($videoViewsArray) . ";
                usernameArray = " . json_encode($usernameArray) . ";
                likesArray = " . json_encode($likesArray) . ";
                titleArray = " . json_encode($titleArray) . ";
                tagArray = " . json_encode($tagArray) . ";
                tagViewsArray = " . json_encode($tagViewsArray) . ";
                imageURLArray = " . json_encode($imageURLArray) . ";
                linksArray = " . json_encode($linksArray) . ";
                tagLinksArray = " . json_encode($tagLinksArray) . ";
            </script>
            ";
        // Display the results using JavaScript
        echo "
            <script>
                generateSectionHeaders();
            </script>
            ";
    }
}
  1. Fetch TikTok Page Content

    • Use file_get_contents($url) to retrieve the content of the TikTok page specified by the given URL.

  2. Initialize Arrays for Data Storage

    • Create arrays to store various data extracted from the TikTok page, including video views, usernames, likes, titles, tags, tag views, image URLs, and links.

  3. Initialize Error Flag

    • Set a flag, $somethingWong, to false initially. This flag will be used to check if something went wrong during the extraction process.

  4. Filter Author Links

    • Load the HTML content into a DOMDocument.

    • Use XPath to find specific <div> elements with the class tiktok-1as5cen-DivWrapper e1cg0wnj1.

    • Extract author anchors (<a> tags) and construct complete URLs by appending them to "https://www.tiktok.com".

    • Store the author links in the linksArray.

  5. Filter Video Views

    • Use XPath to find <strong> elements within a <div> with the class tiktok-k7smtc-DivCoverFooter e1aajktk7.

    • Extract the text content of the <strong> elements, representing the number of likes, and store them in the videoViewsArray.

  6. Filter Usernames

    • Use XPath to find <p> elements with the class tiktok-18g0m3y-PInfo-StyledH3UniqueId e1aajktk12.

    • Extract the text content of the <p> elements, representing usernames, and store them in the usernameArray.

  7. Filter Likes

    • Use XPath to find <span> elements with the class tiktok-1cgeagm-SpanLikes e1aajktk13.

    • Extract the text content of the <span> elements, representing the number of likes, and store them in the likesArray.

  8. Filter Title

    • Use XPath to find <div> elements with the class tiktok-156kx37-DivVideoDescription e1aajktk10.

    • Extract the text content from the 'title' attribute of the <div> elements and store them in the titleArray.

  9. Filter Tags and Views

    • Use XPath to find <div> elements with the class tiktok-1s2ovfk-DivContent eabhyw07 that contain the word 'views'.

    • Extract tag names, views, and construct tag links based on the content of these <div> elements.

    • Store tag names, views, and tag links in tagArray, tagViewsArray, and tagLinksArray, respectively.

    • Set $somethingWong to true if no matching <div> elements are found.

  10. Filter Images

    • Use XPath to find <div> elements with the class tiktok-1jxhpnd-DivContainer e1yey0rl0.

    • Extract image tags (<img> elements) and get the source link (URL) of each image.

    • Store the image URLs in the imageURLArray.

  11. Check for Errors

    • If $somethingWong is true (indicating an issue during tag and view extraction), echo a JavaScript script to call the noResult() function.

  12. Display Results

    • If extraction is successful, echo JavaScript scripts to convert PHP arrays to JavaScript variables.

    • Call the generateSectionHeaders() function to display the results using JavaScript.

PHP for Facebook content

function forFacebook($keyword)
{
    // Construct the Google search URL for images related to the provided keyword on Facebook
    $googleURL = "https://www.google.com/search?rlz=1C1VDKB_enMY1067MY1067&q=" . $keyword . "&tbm=isch&source=lnms&sa=X&ved=2ahUKEwiK_8X6vbCAAxXCzjgGHUSaDxUQ0pQJegQIBxAB&cshid=1690515797708147&biw=1280&bih=595&dpr=1.5";
    // Fetch the content of the Google search results page
    $a = file_get_contents($googleURL);
    $dom = new DOMDocument();
    // Load HTML content into DOMDocument and set up XPath
    libxml_use_internal_errors(true);
    $dom->loadHTML($a);
    libxml_use_internal_errors(false);
    $xpath = new DOMXPath($dom);
    // XPath query to find href attributes of a elements within tables with a specific class
    $aElements = $xpath->query("//table[contains(@class, 'GpQGbf')]//a/@href");
    $processedUrls = array(); // Array to store processed Facebook URLs
    // Loop through the found a elements and extract relevant Facebook URLs
    foreach ($aElements as $aElement) {
        $url = $aElement->nodeValue;
        $parsedUrl = parse_url($url);
        if (isset($parsedUrl['query'])) {
            parse_str($parsedUrl['query'], $query);
            if (isset($query['q'])) {
                $decodedUrl = urldecode($query['q']);
                // Check if the decoded URL contains 'facebook.com'
                if (str_contains($decodedUrl, 'facebook.com')) {
                    // Check for different types of Facebook URLs (posts, photos) and filter accordingly
                    if (str_contains($decodedUrl, "/posts/")) {
                        if (str_contains($decodedUrl, "/groups/")) {
                        } else {
                            // Process Facebook post URLs and remove unwanted parts
                            $test1 = removeUnwantedPart($decodedUrl);
                            if (hasCharsAfterPosts($test1)) {
                                $processedUrls[] = $test1;
                            }
                        }
                    } elseif (str_contains($decodedUrl, "/photos/")) {
                        if (str_contains($decodedUrl, "/groups/")) {
                        } else {
                            // Process Facebook photo URLs with specific conditions
                            if (isSeriesOfNumbersBeforePhotos($decodedUrl)) {
                            } else {
                                $processedUrls[] = $decodedUrl;
                            }
                        }
                    }
                }
            }
        }
    }
    // Check if any processed URLs are found and display them; otherwise, show a no-result message
    if (empty($processedUrls)) {
        echo "<script>noResult();</script>";
    } else {
        // Remove repeating links and display the processed URLs
        displayURL(removeRepeatingLinks($processedUrls));
    }
}
// Check if there is a series of numbers before "/photos/" in the given URL
function isSeriesOfNumbersBeforePhotos($url)
{
    // Regular expression pattern to match a series of numbers before "/photos/"
    $pattern = '/\/(\d+)\/photos\//';
    // Use preg_match to check if the pattern is found in the URL and return a boolean result
    return preg_match($pattern, $url, $matches) === 1;
}
// Check if there are characters after the "/posts/" keyword in the given URL
function hasCharsAfterPosts($url)
{
    // Keyword to search for in the URL
    $keyword = "/posts/";
    // Find the position of the keyword in the URL
    $pos = strpos($url, $keyword);
    // If the keyword is found, check if there are characters after it
    if ($pos !== false) {
        $pos += strlen($keyword);
        return $pos < strlen($url);
    }
    // If the keyword is not found, return false
    return false;
}
// Remove unwanted part of the URL starting from "/posts/" to the next "/"
function removeUnwantedPart($url)
{
    // Starting and ending substrings to identify the part to be removed
    $start = '/posts/';
    $end = '/';
    // Find the starting index of the unwanted part in the URL
    $startIndex = strpos($url, $start);
    // If the starting index is found, proceed to find the ending index
    if ($startIndex !== false) {
        $startIndex += strlen($start);
        $endIndex = strpos($url, $end, $startIndex);
        // If the ending index is found, remove the unwanted part and return the modified URL
        if ($endIndex !== false) {
            return substr($url, 0, $startIndex) . substr($url, $endIndex + 1);
        }
    }
    // If either index is not found, return the original URL
    return $url;
}
// Remove repeating links from the given array of links
function removeRepeatingLinks($links)
{
    $uniqueLinks = array();
    // Loop through each link in the array
    foreach ($links as $link) {
        // Check if the link is not already in the uniqueLinks array and add it if not
        if (!in_array($link, $uniqueLinks)) {
            $uniqueLinks[] = $link;
        }
    }
    // Return the array of unique links
    return $uniqueLinks;
}
// Display processed URLs by echoing JavaScript code to set a variable and trigger a function
function displayURL($processedUrls)
{
    // Echo JavaScript code to set the processedUrls variable with JSON-encoded data
    echo "<script>processedUrls = " . json_encode($processedUrls) . "</script>";
    // Echo JavaScript code to trigger the addLocationBlocks function
    echo "<script>addLocationBlocks();</script>";
}
  1. Initialize Google Search URL:

    • Construct a Google search URL for images related to the provided keyword on Facebook.

  2. Fetch Google Search Results:

    • Use file_get_contents to fetch the content of the Google search results page using the constructed URL.

  3. Create DOMDocument:

    • Create a new DOMDocument to parse the HTML content of the Google search results.

  4. Load HTML into DOMDocument:

    • Load the HTML content into the DOMDocument and set up XPath for querying.

  5. XPath Query for Href Attributes:

    • Use XPath to query for href attributes of <a> elements within tables with a specific class (GpQGbf).

  6. Process Facebook URLs:

    • Loop through the found <a> elements and extract relevant Facebook URLs.

  7. Check for Facebook URLs:

    • Check if the decoded URL contains 'facebook.com'.

  8. Filter Facebook URLs:

    • Differentiate between Facebook post URLs and Facebook photo URLs.

  9. Process Facebook Post URLs:

    • For post URLs, remove unwanted parts and check for characters after "/posts/".

  10. Process Facebook Photo URLs:

    • For photo URLs, apply specific conditions to filter out unwanted URLs.

  11. Check for Series of Numbers in Photo URLs:

    • Use a regular expression to check if there is a series of numbers before "/photos/" in the given URL.

  12. Display Results or No-Result Message:

    • Check if any processed URLs are found, and either display the processed URLs or show a no-result message.

  13. Remove Repeating Links:

    • Remove repeating links from the array of processed URLs to ensure uniqueness.

  14. Display Processed URLs:

    • Echo JavaScript code to set a variable with JSON-encoded data containing the processed URLs.

  15. Trigger JavaScript Function:

    • Echo JavaScript code to trigger the addLocationBlocks function, which likely handles the display of the processed URLs.

Last updated