# GET-PLACES-TIKTOK-FACEBOOK

{% hint style="info" %}
Refer at [github](https://github.com/techkoson/generic-code/tree/main/PHP/get-places-tiktok-facebook) for template (updated at 21 NOV 2023):
{% endhint %}

## Output Screenshots

### TikTok

<figure><img src="/files/KS2qneM02AeBUoFjHSCV" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/PQy1P8wbzmm2iBmHZR74" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/paPkXuawdH0PYnQJ2Kmf" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/LFExiBfCb0evtgaDA7Ia" alt=""><figcaption></figcaption></figure>

### Facebook

<figure><img src="/files/vfmd7GoDlETzq8GBvZr5" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/cSQ5vZfPav9XnIJ7l8tC" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/2reZcOWRhfKFNHXT9VrZ" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/r80nLGM3aq1tWZxoqsh1" alt=""><figcaption></figcaption></figure>

## Implementation on Your Website

### <mark style="color:red;">`form.php`</mark>

```html
<!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 <mark style="color:red;">`platform`</mark> of choice ("tiktok" or "facebook"), <mark style="color:red;">`mainPlace`</mark> (e.g. "Ipoh"), and <mark style="color:red;">`name`</mark> (e.g. "10 Studio Cafe")

### <mark style="color:red;">`get-places-tiktok-facebook.php`</mark>

#### Import

```html
<!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

```html
<!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

```html
    <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

```php
// 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 <mark style="color:red;">`$_POST["platform"]`</mark>.
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 <mark style="color:red;">`showBanner('tiktok')`</mark>.
   * 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 <mark style="color:red;">`$_POST["mainPlace"]`</mark> and <mark style="color:red;">`$_POST["name"]`</mark>.
5. **URL Encode Name and Main Place:**
   * Encode the "name" and "mainPlace" variables using <mark style="color:red;">`urlencode()`</mark>.
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 <mark style="color:red;">`file_get_contents()`</mark>.
     * Parse the HTML content using a <mark style="color:red;">`DOMDocument`</mark> and <mark style="color:red;">`XPath`</mark>.
     * 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 <mark style="color:red;">`forTikTok`</mark> 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 <mark style="color:red;">`forFacebook`</mark> function with the constructed search text.

#### PHP for TikTok content

```php
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 <mark style="color:red;">`file_get_contents($url)`</mark> 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, <mark style="color:red;">`$somethingWong`</mark>, 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 <mark style="color:red;">`DOMDocument`</mark>.
   * Use <mark style="color:red;">`XPath`</mark> to find specific <mark style="color:red;">`<div>`</mark> elements with the class <mark style="color:red;">`tiktok-1as5cen-DivWrapper e1cg0wnj1`</mark>.
   * Extract author anchors (<mark style="color:red;">`<a>`</mark> tags) and construct complete URLs by appending them to "[https://www.tiktok.com](https://www.tiktok.com/)".
   * Store the author links in the <mark style="color:red;">`linksArray`</mark>.
5. **Filter Video Views**
   * Use <mark style="color:red;">`XPath`</mark> to find <mark style="color:red;">`<strong>`</mark> elements within a <mark style="color:red;">`<div>`</mark> with the class <mark style="color:red;">`tiktok-k7smtc-DivCoverFooter e1aajktk7`</mark>.
   * Extract the text content of the <mark style="color:red;">`<strong>`</mark> elements, representing the number of likes, and store them in the <mark style="color:red;">`videoViewsArray`</mark>.
6. **Filter Usernames**
   * Use <mark style="color:red;">`XPath`</mark> to find <mark style="color:red;">`<p>`</mark> elements with the class <mark style="color:red;">`tiktok-18g0m3y-PInfo-StyledH3UniqueId e1aajktk12`</mark>.
   * Extract the text content of the <mark style="color:red;">`<p>`</mark> elements, representing usernames, and store them in the <mark style="color:red;">`usernameArray`</mark>.
7. **Filter Likes**
   * Use <mark style="color:red;">`XPath`</mark> to find <mark style="color:red;">`<span>`</mark> elements with the class <mark style="color:red;">`tiktok-1cgeagm-SpanLikes e1aajktk13`</mark>.
   * Extract the text content of the <mark style="color:red;">`<span>`</mark> elements, representing the number of likes, and store them in the <mark style="color:red;">`likesArray`</mark>.
8. **Filter Title**
   * Use <mark style="color:red;">`XPath`</mark> to find <mark style="color:red;">`<div>`</mark> elements with the class <mark style="color:red;">`tiktok-156kx37-DivVideoDescription e1aajktk10`</mark>.
   * Extract the text content from the 'title' attribute of the <mark style="color:red;">`<div>`</mark> elements and store them in the <mark style="color:red;">`titleArray`</mark>.
9. **Filter Tags and Views**
   * Use <mark style="color:red;">`XPath`</mark> to find <mark style="color:red;">`<div>`</mark> elements with the class <mark style="color:red;">`tiktok-1s2ovfk-DivContent eabhyw07`</mark> that contain the word 'views'.
   * Extract tag names, views, and construct tag links based on the content of these <mark style="color:red;">`<div>`</mark> elements.
   * Store tag names, views, and tag links in <mark style="color:red;">`tagArray`</mark>, <mark style="color:red;">`tagViewsArray`</mark>, and <mark style="color:red;">`tagLinksArray`</mark>, respectively.
   * Set <mark style="color:red;">`$somethingWong`</mark> to true if no matching <mark style="color:red;">`<div>`</mark> elements are found.
10. **Filter Images**
    * Use <mark style="color:red;">`XPath`</mark> to find <mark style="color:red;">`<div>`</mark> elements with the class <mark style="color:red;">`tiktok-1jxhpnd-DivContainer e1yey0rl0`</mark>.
    * Extract image tags (<mark style="color:red;">`<img>`</mark> elements) and get the source link (URL) of each image.
    * Store the image URLs in the <mark style="color:red;">`imageURLArray`</mark>.
11. **Check for Errors**
    * If <mark style="color:red;">`$somethingWong`</mark> is true (indicating an issue during tag and view extraction), echo a JavaScript script to call the <mark style="color:red;">`noResult()`</mark> function.
12. **Display Results**
    * If extraction is successful, echo JavaScript scripts to convert PHP arrays to JavaScript variables.
    * Call the <mark style="color:red;">`generateSectionHeaders()`</mark> function to display the results using JavaScript.

#### PHP for Facebook content

```php
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 <mark style="color:red;">`file_get_contents`</mark> to fetch the content of the Google search results page using the constructed URL.
3. **Create DOMDocument:**
   * Create a new <mark style="color:red;">`DOMDocument`</mark> to parse the HTML content of the Google search results.
4. **Load HTML into DOMDocument:**
   * Load the HTML content into the <mark style="color:red;">`DOMDocument`</mark> and set up <mark style="color:red;">`XPath`</mark> for querying.
5. **XPath Query for Href Attributes:**
   * Use <mark style="color:red;">`XPath`</mark> to query for <mark style="color:red;">`href`</mark> attributes of <mark style="color:red;">`<a>`</mark> elements within tables with a specific class (<mark style="color:red;">`GpQGbf`</mark>).
6. **Process Facebook URLs:**
   * Loop through the found <mark style="color:red;">`<a>`</mark> 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 <mark style="color:red;">`addLocationBlocks`</mark> function, which likely handles the display of the processed URLs.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://technical-gitbook.kosontechnology.com/php/get-places-tiktok-facebook.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
