简体   繁体   English

我如何在PHP中使用simplexml来获取值和节点作为字符串

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

Example, I have an xml code like this: 例如,我有一个这样的xml代码:

$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: 如何使用simplexml捕获标记<desc1>...</desc1>之间的字符串,因此输出如下:

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

thanks in advance :) 提前致谢 :)

You can use DOMDocument then load that xml into it. 您可以使用DOMDocument然后将该xml加载到其中。 Target that desc1 then get its children, save it and put it inside a container string. 然后定位到该desc1的子对象,保存并放入容器字符串中。 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. 作为@Ghost的替代方法,您可以使用Xpath直接获取子节点。

$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: Xpath表达式:

Select all desc1 nodes anywhere in the document: //desc1 选择文档中任何位置的所有desc1节点: //desc1

Limit to the first found node: //desc1[1] 限制为找到的第一个节点: //desc1[1]

Get the child nodes (including text nodes): //desc1[1]/node() 获取子节点(包括文本节点): //desc1[1]/node()

Just an alternative for your specific simple example: 只是您的特定简单示例的替代方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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