简体   繁体   中英

how i can grab value and node as string using simplexml in php

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 :)

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;

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()

Just an alternative for your specific simple example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM