S
S
Shimpanze2017-03-02 06:43:09
XPath
Shimpanze, 2017-03-02 06:43:09

XPath: how to find all nodes of the current variable?

Hello!
WordPress has a $content variable.
I need to wrap EVERY root node inside this variable in a div tag, so it looks like this:

<div class="parent"><i>Расписание</i></div>
<div class="parent"><i>Расписание</i></div>
<div class="parent"><i>Расписание</i></div>

I do it like this:
$cont = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' );
$dom = new DomDocument();
$dom->loadHTML( $content );
$xpath = new DomXPath( $dom );

foreach( $xpath->query( './/*' ) as $element ) {

  return "<div class=\"parent\">" . $element->C14N() . PHP_EOL . "</div>" . PHP_EOL;

}

But it wraps ALL the contents of that variable in a div, not every node. And it turns out like this:
<div class="parent">
<i>Расписание</i>
<i>Расписание</i>
<i>Расписание</i>
</div>

Why doesn't it iterate over all the elements inside the variable somewhere? After all, everything is written correctly.
I've already tried it like this: $xpath->query( $content ), - it still doesn't sort into any.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Pupkin, 2017-03-02
@Shimpanze

<?php

$content = '
<i>Расписание</i>
<i>Расписание</i>
<i>Расписание</i>';

$cont = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' );
$dom = new DomDocument();
$dom->loadHTML( $content );
$xpath = new DomXPath( $dom );

foreach( $xpath->query( './/i' ) as $element ) {
  	echo "<div class=\"parent\">" . $element->C14N() . PHP_EOL . "</div>" . PHP_EOL;

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question