php 关联数组、正则表达式、数组

发布于 2024-09-14 18:24:44 字数 641 浏览 3 评论 0原文

我目前有以下代码:

$content = "
<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>";

我需要找到一种方法来创建和数组为 name=>value。例如制造商=>约翰迪尔

任何人都可以帮助我剪断一个简单的代码,我尝试了一些正则表达式,但甚至无法提取名称或值,例如:

$pattern = "/<name>Manufacturer<\/name><value>(.*)<\/value>/";
preg_match_all($pattern, $content, $matches);
$st_selval = $matches[1][0];

I currently have the following code :

$content = "
<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>";

I need to find a method to create and array as name=>value. E.g Manufacturer => John Deere.

Can anyone help me with a simple code snipped I tried some regex but doesn't even work to extract the names or values, e.g.:

$pattern = "/<name>Manufacturer<\/name><value>(.*)<\/value>/";
preg_match_all($pattern, $content, $matches);
$st_selval = $matches[1][0];

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

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

发布评论

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

评论(7

热情消退 2024-09-21 18:24:45

您不想为此使用正则表达式。尝试类似 SimpleXML

编辑
好吧,为什么不从这个开始:

<?php

$content = "<root>" . $content . "</root>";
$xml = new SimpleXMLElement($c);
print_r($xml);

?>

编辑 2
尽管使用正则表达式发布的一些答案可能有效,但您应该养成使用正确工具来完成工作的习惯,并且正则表达式不是解析 XML 的正确工具。

You don't want to use regex for this. Try out something like SimpleXML

EDIT
Well, why don't you start with this:

<?php

$content = "<root>" . $content . "</root>";
$xml = new SimpleXMLElement($c);
print_r($xml);

?>

EDIT 2
Despite the fact that some of the answers posted using regular expression MAY work, you should get in the habit of using the correct tool for the job and regular expressions are not the correct tool for parsing of XML.

瑶笙 2024-09-21 18:24:45

我正在使用您的 $content 变量:

$preg1 = preg_match_all('#<name>([^<]+)#', $content, $name_arr);
$preg2 = preg_match_all('#<value>([^<]+)#', $content, $val_arr);
$array = array_combine($name_arr[1], $val_arr[1]);

I'm using your $content variable:

$preg1 = preg_match_all('#<name>([^<]+)#', $content, $name_arr);
$preg2 = preg_match_all('#<value>([^<]+)#', $content, $val_arr);
$array = array_combine($name_arr[1], $val_arr[1]);
标点 2024-09-21 18:24:45

这个问题比较简单,可以通过正则表达式来解决。应该是:

$name  = '<name>\s*([^<]+)</name>\s*';
$value = '<value>\s*([^<]+)</value>\s*';

$pattern = "|$name $value|";
preg_match_all($pattern, $content, $matches);

# create hash
$stuff = array_combine($matches[1], $matches[2]);

# display
var_dump($stuff);

问候

rbo

This is rather simple, can be solved by regex. Should be:

$name  = '<name>\s*([^<]+)</name>\s*';
$value = '<value>\s*([^<]+)</value>\s*';

$pattern = "|$name $value|";
preg_match_all($pattern, $content, $matches);

# create hash
$stuff = array_combine($matches[1], $matches[2]);

# display
var_dump($stuff);

Regards

rbo

写下不归期 2024-09-21 18:24:45

首先,永远不要使用 正则表达式 来解析 xml ...

您可以使用 XPATH 查询来完成此操作...

首先,将内容包装在根标记中以使解析器满意(如果还没有):

$content = '<root>' . $content . '</root>';

然后,加载文档

$dom = new DomDocument();
$dom->loadXml($content);

然后,初始化 XPATH

$xpath = new DomXpath($dom);

编写您的查询:

$xpathQuery = '//name[text()="Manufacturer"]/follwing-sibling::value/text()';

然后执行它:

$manufacturer = $xpath->evaluate($xpathQuery);

如果我正确执行了 xpath,则 $manufacturer 应该是 John Deere...

您可以在 $manufacturer 上查看文档a href="http://php.net/manual/en/class.domxpath.php" rel="nofollow noreferrer">DomXpath,a XPath 基础入门,以及 一堆 XPath 示例...

编辑:这行不通(PHP 不支持该语法(以下同级)。您可以这样做,而不是xpath查询:

$xpathQuery = '//name[text()="Manufacturer"]';
$elements = $xpath->query($xpathQuery);
$manufacturer = $elements->item(0)->nextSibling->nodeValue;

First of all, never use regex to parse xml...

You could do this with an XPATH query...

First, wrap the content in a root tag to make the parser happy (if it doesn't already have it):

$content = '<root>' . $content . '</root>';

Then, load the document

$dom = new DomDocument();
$dom->loadXml($content);

Then, initialize the XPATH

$xpath = new DomXpath($dom);

Write your query:

$xpathQuery = '//name[text()="Manufacturer"]/follwing-sibling::value/text()';

Then, execute it:

$manufacturer = $xpath->evaluate($xpathQuery);

If I did the xpath right, it $manufacturer should be John Deere...

You can see the docs on DomXpath, a basic primer on XPath, and a bunch of XPath examples...

Edit: That won't work (PHP doesn't support that syntax (following-sibling). You could do this instead of the xpath query:

$xpathQuery = '//name[text()="Manufacturer"]';
$elements = $xpath->query($xpathQuery);
$manufacturer = $elements->item(0)->nextSibling->nodeValue;
同尘 2024-09-21 18:24:45

我认为这就是您正在寻找的:

<?php
$content = "<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>";
$pattern = "(\<name\>(\w*)\<\/name\>\<value\>(\w*)\<\/value\>)";
preg_match_all($pattern, $content, $matches);

$arr = array();

for ($i=0; $i<count($matches); $i++){
    $arr[$matches[1][$i]] = $matches[2][$i];    
}

/* This is an example on how to use it */
echo "Location: " . $arr["Location"] . "<br><br>";

/* This is the array */
print_r($arr);

?>

如果数组有很多元素,请不要在 for 循环中使用 count() 函数,请先计算值,然后将其用作常量。

I think this is what you're looking for:

<?php
$content = "<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>";
$pattern = "(\<name\>(\w*)\<\/name\>\<value\>(\w*)\<\/value\>)";
preg_match_all($pattern, $content, $matches);

$arr = array();

for ($i=0; $i<count($matches); $i++){
    $arr[$matches[1][$i]] = $matches[2][$i];    
}

/* This is an example on how to use it */
echo "Location: " . $arr["Location"] . "<br><br>";

/* This is the array */
print_r($arr);

?>

If your array has a lot of elements dont use the count() function in the for loop, calculate the value first and then use it as a constant.

疧_╮線 2024-09-21 18:24:45

我将进行编辑,因为我的 PHP 是错误的,但这里有一些 PHP(伪)代码可以提供一些指导。

$pattern = '|<name>([^<]*)</name>\s*<value>([^<]*)</value>|'
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);
for($i = 0; $i < count($matches); $i++) {
    $arr[$matches[$i][1]] = $matches[$i][2];
}

$arr 是要存储名称/值对的数组。

I'll edit as my PHP is wrong, but here's some PHP (pseudo-)code to give some direction.

$pattern = '|<name>([^<]*)</name>\s*<value>([^<]*)</value>|'
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);
for($i = 0; $i < count($matches); $i++) {
    $arr[$matches[$i][1]] = $matches[$i][2];
}

$arr is the array you want to store the name/value pairs.

多情出卖 2024-09-21 18:24:45

使用 XMLReader

$content = '<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>';
$content = '<content>' . $content . '</content>';
$output = array();

$reader = new XMLReader();
$reader->XML($content);
$currentKey = null;
$currentValue = null;
while ($reader->read()) {
    switch ($reader->name) {
        case 'name':
            $reader->read();
            $currentKey = $reader->value;
            $reader->read();
            break;
        case 'value':
            $reader->read();
            $currentValue = $reader->value;
            $reader->read();
            break;
    }
    if (isset($currentKey) && isset($currentValue)) {
        $output[$currentKey] = $currentValue;
        $currentKey = null;
        $currentValue = null;
    }
}

print_r($output);

输出为:

Array
(
    [Manufacturer] => John Deere
    [Year] => 2001
    [Location] => NSW
    [Hours] => 6320
)

Using XMLReader:

$content = '<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>';
$content = '<content>' . $content . '</content>';
$output = array();

$reader = new XMLReader();
$reader->XML($content);
$currentKey = null;
$currentValue = null;
while ($reader->read()) {
    switch ($reader->name) {
        case 'name':
            $reader->read();
            $currentKey = $reader->value;
            $reader->read();
            break;
        case 'value':
            $reader->read();
            $currentValue = $reader->value;
            $reader->read();
            break;
    }
    if (isset($currentKey) && isset($currentValue)) {
        $output[$currentKey] = $currentValue;
        $currentKey = null;
        $currentValue = null;
    }
}

print_r($output);

The output is:

Array
(
    [Manufacturer] => John Deere
    [Year] => 2001
    [Location] => NSW
    [Hours] => 6320
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文