Search code examples
phpvariablesxpathextracthref

Why is my echo'd PHP variable still producing nothing?


I recently was provided an excellent answer on how to handle extracting my URL from HTML content here:

Extracting context from a set point in the middle of an HTML file

But after implementing the code, I still show nothing from the echo call on the variable afterwards. I know if I echo get_the_content(), it shows the entire post body as it should, but maybe its not being handled properly by loadHTML()? I implemented the code as provided (which to my knowledge works perfectly aka no errors) and within the foreach loop assigned the extracted URL to a variable so I could use it in the location necessary, as shown by the code below:

<?php
    $doc   = new DOMDocument();
    $doc->strictErrorChecking = FALSE;
    $xpath = new DOMXpath($doc);

    $a = 1;
    if (have_posts()) :
        while ( have_posts() ) : the_post();
?>
<div class="ORtrack">
    <?php
        $success = $doc->loadHTML(get_the_content());
        if ($success === FALSE) {
            // error handling
        } else {
            $hrefs = $xpath->query("//a[contains(@href,'mp3')]/@href");
            foreach ($hrefs as $href) {
                $BEmp3s = $href;
            }
        };
    ?>
<script type="text/javascript">
    var myCP<?php echo $a; ?> = new CirclePlayer("#jquery_jplayer_<?php echo $a; ?>",
    {
        mp3: "<?php echo $BEmp3s; ?>"
    }, {
        cssSelectorAncestor: "#cp_container_<?php echo $a; ?>",
        volume: 0.5
    });
</script>
    ....
<?php
    endif;
    wp_reset_query();
?>
</div>

There is only ONE MP3 URL to grab per Post body and I always want the first one if for some reason there does end up being multiple MP3 URL's, so is it really necessary to build the array? What am I still missing and is this the most efficient manner to accomplish this?


Solution

  • If there's only one MP3 being returned by your xpath, then don't use a foreach loop. That's overkill. A single item can be retrieved by doing

    $BEmp3s = $hrefs->item(0)
    

    and you can check if the xpath actually found anything via

    if ($hrefs->length > 0) { ... found something ... }