1

Example, I have an xml code like this:

$xml=<<<XML
<?xml version="1.0"?>
<cars>
  <desc1>
       <h1>Title 1</h1>
       <p>Content</p>
  </desc1>
  <desc2>
       <h1>Title 1</h1>
       <p>Content</p>
  </desc2> 
</cars>
XML;

How can I grab string between tag <desc1>...</desc1> using simplexml so the output like this:

$output='<h1>Title 1</h1>
           <p>Content</p>';

thanks in advance :)

3 Answers 3

1

You can use DOMDocument then load that xml into it. Target that desc1 then get its children, save it and put it inside a container string. Example:

$dom = new DOMDocument();
$dom->loadXML($xml);

$output = '';
$desc1 = $dom->getElementsByTagName('desc1')->item(0)->childNodes;
foreach ($desc1 as $children) {
    $output .= $dom->saveHTML($children);
}

echo $output;
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for fast replay, but when i execute the code, i got an error like Warning: DOMDocument::saveHTML() expects exactly 0 parameters, 1 given @ghost
yeah, i got it,..... the problem is in php ver 5.3.5 for property of DOMDocument::saveHTML() doesnt accept param, so i upgrade my php to 5.5.x and its work like charm... DOMDocument::saveHTML($param) introduce at php ver 5.3.6... thx :)
@mgx oh okay, img glad this helped, you might also want to take a look at ThW's answer as it is also good alternatively to it
1

As an alternative to @Ghost you could use Xpath to fetch the child nodes directly.

$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXpath($dom);

$output = '';
foreach ($xpath->evaluate('//desc1[1]/node()') as $child) {
    $output .= $dom->saveHTML($child);
}

echo $output;

The Xpath expression:

Select all desc1 nodes anywhere in the document: //desc1

Limit to the first found node: //desc1[1]

Get the child nodes (including text nodes): //desc1[1]/node()

Comments

-1

Just an alternative for your specific simple example:

$output = "";
if(preg_match("/<desc1>[^<]*(<.*>)[^>]*<\/desc1>/s",$xml,$reg)) {
  $output = $reg[1];
}

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.