PHP 对象的 XPath 结果

发布于 2024-08-19 20:15:37 字数 492 浏览 5 评论 0原文

我有一个 xml 文件,它代表许多对象,我在应用程序中有一个类。例如,博客文章:

<blogposts>
  <blogpost id="604">
    <title>afdghadfh</title>
    <body>adfgadfgda</body>
  </blogpost>
  <blogpost id="605">
    <title>dafghadh</title>
    <body>afadf</body>
  </blogpost>
</blogposts> 

我想使用 XPath 读取 xml 文件并将结果转换为博客文章对象。是否有任何简单的方法可以将生成的 SimpleXMLElement 对象转换为 blogpost 对象的值?

任何建议表示赞赏。

谢谢。

I have an xml file which represents a number of objects for which I have a class in my application. For example, blogposts:

<blogposts>
  <blogpost id="604">
    <title>afdghadfh</title>
    <body>adfgadfgda</body>
  </blogpost>
  <blogpost id="605">
    <title>dafghadh</title>
    <body>afadf</body>
  </blogpost>
</blogposts> 

I would like to read the xml file using XPath and convert the results to blogpost objects. Is there any simple way to convert the resulting SimpleXMLElement Objects into values for a blogpost object?

Any advice appreciated.

Thanks.

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

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

发布评论

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

评论(1

九八野马 2024-08-26 20:15:37

根据需要进行调整。

// blogpost class definition

$blogposts = array();

$xml_resource = new SimpleXMLElement('file.xml', 0, true);

foreach($xml_resource->xpath('/blogposts/blogpost') as $blogpost)
{
    $current_blogpost = new blogpost();
    $current_blogpost->id = (int) $blogpost['id'];
    $current_blogpost->title = (string) $blogpost->title;
    $current_blogpost->body = (string) $blogpost->body;
    $blogposts[] = $current_blogpost;
}

Tweak as needed.

// blogpost class definition

$blogposts = array();

$xml_resource = new SimpleXMLElement('file.xml', 0, true);

foreach($xml_resource->xpath('/blogposts/blogpost') as $blogpost)
{
    $current_blogpost = new blogpost();
    $current_blogpost->id = (int) $blogpost['id'];
    $current_blogpost->title = (string) $blogpost->title;
    $current_blogpost->body = (string) $blogpost->body;
    $blogposts[] = $current_blogpost;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文