-1

I have HTML output of the form:

<!-- wp:uagb/section {"block_id":"e00ee750-246d-46fd-a034-c6dc37497309","contenttype":"exercise","contenttitle":"here is exercise 1","contentname":"Exercise"} -->
<div id="here-is-exercise-1" class="contenttype-wrapper sometopictype-exercise" data-id="e00ee750-246d-46fd-a034-c6dc37497309">
<!-- wp:paragraph -->
   <p>Some stuff</p>
<!-- /wp:paragraph -->
</div>
<!-- /wp:uagb/section -->

So you have these comments that start with <!-- wp:uagb/section and in those comments you have JSON of form

{"block_id":"e00ee750-246d-46fd-a034-c6dc37497309","contenttype":"exercise","contenttitle":"here is exercise 1","contentname":"Exercise"}

I am trying to form an XPATH query (in PHP) that is of form

"Get me all JSON objects that contain parameter `contenttype`"

I am pretty proficient with XPATH when it comes to normal DOM extraction, but not quite sure how to go about this. Ideas?

5
  • Is your desired output the whole first comment or just the word `exercise'? Commented Dec 7, 2019 at 11:44
  • The JSON object is what is needed Commented Dec 7, 2019 at 14:29
  • Then the xpath expression in the first line of your answer (//comment()[contains(.,'contenttype')]) should work, why would you need the rest? Commented Dec 7, 2019 at 14:33
  • If I just call xpath that way, won't it also return the text 'wp:uagb/section' in returned output? Commented Dec 7, 2019 at 16:05
  • No, just the json comment. Commented Dec 7, 2019 at 16:46

1 Answer 1

0

Ok, based on this post

Extracting Comments from HTML code using Xpath

here is what I came up with:

$contenttypes = $xpath->query("//comment()[contains(.,'contenttype')]");
foreach ($contenttypes as $contenttype) {
    preg_match_all("/\\{(.*?)\\}/", $contenttype->data, $matches);
    $data = json_decode(trim($matches[0][0], '"')); 

And then the data I need is in that $data variable. Didn't realize that xpath has built in support for comments!

I am sure someone has a way to get the JSON object in one xpath query. I couldn't figure that out so just went with preg_match_all.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.