使用 PHP 检索 XML 节点的子集

发布于 2024-08-14 10:28:51 字数 936 浏览 4 评论 0原文

使用 PHP,如何从 XML 文档获取整个节点子集?我可以检索类似的内容:

<?xml version="1.0" encoding="utf-8"?>
<people>
  <certain>
    <name>Jane Doe</name>
    <age>21</age>
  </certain>
  <certain>
  <certain>
    <name>John Smith</name>
    <age>34</age>
  </certain>
</people>

但是如果我只想返回这样的子节点怎么办?

  <certain>
    <name>Jane Doe</name>
    <age>21</age>
  </certain>
  <certain>
  <certain>
    <name>John Smith</name>
    <age>34</age>
  </certain>

编辑:我试图获取 XML 的子集并直接传递它,而不是像 simplexml 这样的对象会给我。我基本上试图让 PHP 做 .NET 的 OuterXml 所做的事情...按原样返回上面的 XML 子集...没有解释或转换或创建新的 XML 文件或任何东西...只需就地提取这些节点并将它们传递下去。我是否必须获取 XML 文件,解析出我需要的内容,然后将其重建为新的 XML 文件?如果是这样,那么我需要摆脱 位...呃。

Using PHP, how do I get an entire subset of nodes from an XML document? I can retrieve something like:

<?xml version="1.0" encoding="utf-8"?>
<people>
  <certain>
    <name>Jane Doe</name>
    <age>21</age>
  </certain>
  <certain>
  <certain>
    <name>John Smith</name>
    <age>34</age>
  </certain>
</people>

But what if I only want to return the child nodes of like this?

  <certain>
    <name>Jane Doe</name>
    <age>21</age>
  </certain>
  <certain>
  <certain>
    <name>John Smith</name>
    <age>34</age>
  </certain>

EDIT: I'm trying to get a subset of XML and pass that directly, not an object like simplexml would give me. I am basically trying to get PHP to do what .NET's OuterXml does... return literally the above subset of XML as is... no interpreting or converting or creating a new XML file or anything... just extract those nodes in situ and pass them on. Am I going to have to get the XML file, parse out what I need and then rebuild it as a new XML file? If so then I need to get rid of the <?xml version="1.0" encoding="utf-8"?> bit... ugh.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

窗影残 2024-08-21 10:28:52

答案是 xpath 建议和 asXML() 输出的组合。

使用乔什·戴维斯给出的例子:

$people = simplexml_load_string(
      <?xml version="1.0" encoding="utf-8"?>
        <people>
          <certain>
            <name>Jane Doe</name>
            <age>21</age>
          </certain>
          <certain>
            <name>John Smith</name>
            <age>34</age>
          </certain>
        </people>'
    );

    // get all <certain/> nodes
    $nodes = $people->xpath('/people/certain');

    foreach ( $nodes as $node ) {
      $result .= $node->asXML()."\n";
    }
    echo $result;

The answer turned out to be a combination of the xpath suggestion and outputting with asXML().

Using the example given by Josh Davis:

$people = simplexml_load_string(
      <?xml version="1.0" encoding="utf-8"?>
        <people>
          <certain>
            <name>Jane Doe</name>
            <age>21</age>
          </certain>
          <certain>
            <name>John Smith</name>
            <age>34</age>
          </certain>
        </people>'
    );

    // get all <certain/> nodes
    $nodes = $people->xpath('/people/certain');

    foreach ( $nodes as $node ) {
      $result .= $node->asXML()."\n";
    }
    echo $result;
凤舞天涯 2024-08-21 10:28:51

答案是使用 XPath

$people = simplexml_load_string(
    '<?xml version="1.0" encoding="utf-8"?>
    <people>
      <certain>
        <name>Jane Doe</name>
        <age>21</age>
      </certain>
      <certain>
        <name>John Smith</name>
        <age>34</age>
      </certain>
    </people>'
);

// get all <certain/> nodes
$people->xpath('//certain');

// get all <certain/> nodes whose <name/> is "John Smith"
print_r($people->xpath('//certain[name = "John Smith"]'));

// get all <certain/> nodes whose <age/> child's value is greater than 21
print_r($people->xpath('//certain[age > 21]'));

Take 2

显然你想将一些节点从一个文档复制到另一个文档中? SimpleXML 不支持这一点。 DOM 有一些方法,但使用起来有点烦人。您使用的是哪一款?这是我使用的:SimpleDOM。事实上,它实际上是用 DOM 方法增强的 SimpleXML。

include 'SimpleDOM.php';
$results = simpledom_load_string('<results/>');

foreach ($people->xpath('//certain') as $certain)
{
    $results->appendChild($certain);
}

该例程通过 XPath 查找所有 节点,然后将它们附加到新文档中。

The answer would be to use XPath.

$people = simplexml_load_string(
    '<?xml version="1.0" encoding="utf-8"?>
    <people>
      <certain>
        <name>Jane Doe</name>
        <age>21</age>
      </certain>
      <certain>
        <name>John Smith</name>
        <age>34</age>
      </certain>
    </people>'
);

// get all <certain/> nodes
$people->xpath('//certain');

// get all <certain/> nodes whose <name/> is "John Smith"
print_r($people->xpath('//certain[name = "John Smith"]'));

// get all <certain/> nodes whose <age/> child's value is greater than 21
print_r($people->xpath('//certain[age > 21]'));

Take 2

So apparently you want to copy some nodes from a document into another document? SimpleXML doesn't support that. DOM has methods for that but they're kind of annoying to use. Which one are you using? Here's what I use: SimpleDOM. In fact, it's really SimpleXML augmented with DOM's methods.

include 'SimpleDOM.php';
$results = simpledom_load_string('<results/>');

foreach ($people->xpath('//certain') as $certain)
{
    $results->appendChild($certain);
}

That routine finds all <certain/> node via XPath, then appends them to the new document.

夏有森光若流苏 2024-08-21 10:28:51

您可以使用 DOMDocument.GetElementsByTagName <强>或者你可以:

使用 XPath?

<?php
$xml = simplexml_load_file("test.xml");

$result = $xml->xpath("//certain");

print_r($result);
?>

You could use DOMDocument.GetElementsByTagName or you could:

Use XPath?

<?php
$xml = simplexml_load_file("test.xml");

$result = $xml->xpath("//certain");

print_r($result);
?>
放低过去 2024-08-21 10:28:51

使用 DOM 和 XPath。 Xpath 允许您从 XML DOM 选择节点(和值)。

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

$result = '';
foreach ($xpath->evaluate('/people/certain') as $node) {
  $result .= $dom->saveXml($node);
}

echo $result;

演示: https://eval.in/162149

DOMDocument::saveXml() 有一个上下文参数。如果提供的话,它会将该节点保存为 XML。很像outerXml()。 PHP 也能够为 DOM 节点注册您自己的类。因此,甚至可以向元素节点添加 outerXML() 函数。

class MyDomElement extends DOMElement {
  public function outerXml() {
    return $this->ownerDocument->saveXml($this);
  }
}

class MyDomDocument extends DOMDocument {
  public function __construct($version = '1.0', $encoding = 'utf-8') {
    parent::__construct($version, $encoding);
    $this->registerNodeClass('DOMElement', 'MyDomElement');
  }
}

$dom = new MyDomDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

$result = '';
foreach ($xpath->evaluate('/people/certain') as $node) {
  $result .= $node->outerXml();
}

echo $result;

演示:https://eval.in/162157

Use DOM and XPath. Xpath allows you to select nodes (and values) from an XML DOM.

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

$result = '';
foreach ($xpath->evaluate('/people/certain') as $node) {
  $result .= $dom->saveXml($node);
}

echo $result;

Demo: https://eval.in/162149

DOMDocument::saveXml() has a context argument. If provided it saves that node as XML. Much like outerXml(). PHP is able to register your own classes for the DOM nodes, too. So it is even possible to add an outerXML() function to element nodes.

class MyDomElement extends DOMElement {
  public function outerXml() {
    return $this->ownerDocument->saveXml($this);
  }
}

class MyDomDocument extends DOMDocument {
  public function __construct($version = '1.0', $encoding = 'utf-8') {
    parent::__construct($version, $encoding);
    $this->registerNodeClass('DOMElement', 'MyDomElement');
  }
}

$dom = new MyDomDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);

$result = '';
foreach ($xpath->evaluate('/people/certain') as $node) {
  $result .= $node->outerXml();
}

echo $result;

Demo: https://eval.in/162157

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文