0

I want to take an existing element and put a child inside of it. But I want the content of the pre-existing element to go inside the new element as well.

So I have <span class="folnum">Content</span> and I want to end up with <span class="folnum"><a href="link">content</a></span> and I was hoping I could do this with php's simpleXML parser.

Here's what I've got so far:

$folnum = $xmldoc->xpath("//span[@class='folnum']");
foreach ($folnum as $indivfolnum)
{
    $child = $indivfolnum->addChild("a", "wholemsImage");
    $child->addAttribute("href", (string) $indivfolnum);
}

What I get from this is <span class="folnum">Content<a href="link">wholemsImage</a></span>.

Obviously the addChild() method is adding new content as well, which is not really what I want. I want it to replace the text-content.

1 Answer 1

2

I think this should work:

  1. Save the Content to new variable: $link = (string) $indivfolnum;
  2. Clear the <span> element: $indivfolnum[0] = "";
  3. Then append new child.

Code example:

$folnum = $xmldoc->xpath("//span[@class='folnum']");
foreach ($folnum as $indivfolnum)
{
    $link = (string) $indivfolnum;
    $indivfolnum[0] = "";
    $child = $indivfolnum->addChild("a", "wholemsImage");
    $child->addAttribute("href", $link);
}

It creates the output as you want it:

<span class="folnum"><a href="Content">wholemsImage</a></span>

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

6 Comments

That's a clever idea. But it looks to me like it doesn't work. I get the following error: Fatal error: Call to a member function addChild() on a non-object in /home/jeffr306/public_html/plaoul/text/textdisplay.php on line 145
I think the problem that the addChild method only works on an "simpleXML" object. But when we declare $indivfolnum as empty we are declaring at it as absolutely null, not as an empty "simpleXML" object.
@Jeff: here's a different approach: start one lvl higher (not from <span> element), check if ($body['span'] = 'content') $body['span'] = '<a href="link">content</a>'
SimpleXMLElement::addChild() requires at least PHP 5.1.3. You did get the fatal error because your PHP version was too low.
|

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.