【发布时间】:2014-12-05 16:55:13
【问题描述】:
希望你能帮我解决一个小问题。
我看到了这篇文章,但仍然有一些错误:How to convert HTML to JSON using PHP?
我创建了一个 PHP 文件,它使用这种格式从 wordpress 中获取帖子
<h1><img src="category1.jpg" />Category 1</h1>
<ul>
<li>some text.<strong><em>AUTHOR 1</em></strong></li>
<li>some other text.<strong><em>AUTHOR 2</em></strong></li>
<li>some othe other text.<strong><em>AUTHOR 3</em></strong></li>
</ul>
<h1><img src="category2.jpg" />Category 2</h1>
<ul>
<li>some new text.<strong><em>AUTHOR 4</em></strong></li>
<li>some other new text.<strong><em>AUTHOR 5</em></strong></li>
<li>some othe other new text.<strong><em>AUTHOR 6</em></strong></li>
</ul>
我想要实现的是 json 对象如下所示:
[
{
category: "Category 1", content: [
{text: "some text.", author:"AUTHOR 1"},
{text: "some other text.", author:"AUTHOR 2"},
{text: "some other other text.", author:"AUTHOR 3"},
]
},
{
category: "Category 2", content: [
{text: "some new text.", author:"AUTHOR 4"},
{text: "some other new text.", author:"AUTHOR 5"},
{text: "some other other new text.", author:"AUTHOR 6"},
]
}
之后我需要将它用于 Angular 模块。
有什么解决办法吗?有什么功能吗?
非常感谢!
【问题讨论】:
-
标记中没有任何内容表明给定注释包含作者或类别信息。我们可以做的唯一事情是假设一个h1标签的内容是一个类别名称,而一个
li > strong > em的值就是作者,但是这样的假设是风险极大。另外:向我们展示您的尝试! -
非常感谢!假设我可以接受这些假设,您说没有 PHP 现有函数可以执行与我想要的结果类似的操作?我已经在很长的字符串上尝试了 json_encode() 并且似乎我得到了与输出相同的长字符串。我也尝试过这里的答案中的建议:stackoverflow.com/questions/23062537/… 这让我更进一步,但仍然出现“为 foreach() 提供的参数无效”的一些错误
-
我建议查看正则表达式以匹配您所追求的各种模式。这有点繁琐,涉及各种循环,但应该是可行的。
-
是的,谢谢!我想我可以以某种方式避免使用它,但如果我不得不使用它。
-
@Novocaine: 不要在 DOM 上使用正则表达式 解析标记,提取您需要的节点,并在构造一个数组,简单易用并且可靠。
标签: php html json wordpress angularjs